commit f4504f6413ce4509604dad66cdd689000a0204dc Author: Marvis Date: Mon Nov 23 01:15:26 2026 +0100 Initial commit Rust workspace for VIctory: PE analysis, loader, HLE skeleton, DXBC/DXIL parsing with a GFX10 decoder, conversion cache, CLI and asset-policy enforcement. Co-Authored-By: Claude Sonnet 5.5 diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..9741f11 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run --quiet --package xtask --" diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e06f16e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +# The repository is text-only by policy (see docs/asset-policy.md). +* text=auto eol=lf +*.cmd text eol=crlf +*.ps1 text eol=crlf diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..1b89c97 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,3 @@ +#!/bin/sh +# Enforces the asset policy on every commit. Install with: cargo xtask install-hooks +exec cargo xtask policy --staged diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..365392f --- /dev/null +++ b/.gitignore @@ -0,0 +1,76 @@ +# --------------------------------------------------------------------------- +# RULE #1: nothing from the game (or any other proprietary source) is ever +# committed. +# Everything is built from files the user supplies at runtime. +# This file is the first line of defence; `cargo xtask policy` (also run by +# the pre-commit hook in .githooks/) is the second and is authoritative. +# See docs/asset-policy.md. +# --------------------------------------------------------------------------- + +# Build output +/target/ +/tests/fixtures/*/target/ + +# Local configuration (contains paths to YOUR files) +/victory.toml + +# Places people tend to drop data into. Keep data outside the repo instead. +/game/ +/games/ +/assets/ +/data/ +/dump/ +/dumps/ +/extracted/ +/cache/ +/out/ + +# Executables, libraries, symbols +*.exe +*.dll +*.pdb +*.lib +*.sys +*.obj +*.exp +*.ilk + +# Console packages and containers +*.xvd +*.xvc +*.msixvc +*.xsp +*.cab +*.msi + +# Typical game data (non-exhaustive on purpose; the policy check is an allowlist) +*.bin +*.dat +*.pak +*.rpf +*.dds +*.ktx +*.ktx2 +*.dxbc +*.dxil +*.cso +*.spv +*.wav +*.xma +*.ogg +*.opus +*.mp3 +*.mp4 +*.bik +*.bk2 +*.awc +*.zip +*.7z +*.rar + +# Editor / OS noise +.vs/ +.idea/ +*.swp +Thumbs.db +.DS_Store diff --git a/.victory-root b/.victory-root new file mode 100644 index 0000000..b482750 --- /dev/null +++ b/.victory-root @@ -0,0 +1,5 @@ +This marker file identifies the root of the VIctory source tree. + +Tools refuse to write game-derived output (caches, converted assets, prepared +images, logs containing game data) anywhere below a directory that contains +this file. See docs/asset-policy.md. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..e005915 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,780 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "object" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11dbdb66876026054e4ffc8d757d862bdf5df5aebd5c0b95a41f17832a94f7d2" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "toml" +version = "1.2.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "victory" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "clap", + "memchr", + "victory-core", + "victory-game", + "victory-hle", + "victory-loader", + "victory-pe", + "victory-shader", + "walkdir", +] + +[[package]] +name = "victory-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "serde", + "tempfile", + "thiserror", + "toml", + "tracing-subscriber", +] + +[[package]] +name = "victory-formats" +version = "0.1.0" + +[[package]] +name = "victory-game" +version = "0.1.0" + +[[package]] +name = "victory-gpu" +version = "0.1.0" + +[[package]] +name = "victory-hle" +version = "0.1.0" +dependencies = [ + "tempfile", + "tracing", + "victory-loader", + "victory-pe", + "windows-sys", +] + +[[package]] +name = "victory-loader" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "tempfile", + "thiserror", + "tracing", + "victory-core", + "victory-pe", + "windows-sys", +] + +[[package]] +name = "victory-pe" +version = "0.1.0" +dependencies = [ + "object", + "thiserror", +] + +[[package]] +name = "victory-pipeline" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "tempfile", + "tracing", + "victory-core", +] + +[[package]] +name = "victory-shader" +version = "0.1.0" +dependencies = [ + "miniz_oxide", + "thiserror", +] + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "walkdir", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..a47c64f --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,56 @@ +[workspace] +resolver = "3" +members = ["crates/*", "apps/*", "xtask"] +# Fixtures are standalone crates built on demand by integration tests. +exclude = ["tests/fixtures"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.88" +license = "GPL-3.0-or-later" +publish = false + +[workspace.dependencies] +# Internal crates +victory-core = { path = "crates/victory-core" } +victory-pe = { path = "crates/victory-pe" } +victory-loader = { path = "crates/victory-loader" } +victory-hle = { path = "crates/victory-hle" } +victory-gpu = { path = "crates/victory-gpu" } +victory-shader = { path = "crates/victory-shader" } +victory-formats = { path = "crates/victory-formats" } +victory-pipeline = { path = "crates/victory-pipeline" } +victory-game = { path = "crates/victory-game" } + +# External crates +anyhow = "1.0.104" +thiserror = "2.0.21" +clap = { version = "4.6.9", features = ["derive"] } +tracing = "0.1.44" +tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +serde = { version = "1.0.229", features = ["derive"] } +toml = "1.2.2" +object = { version = "0.41.0", default-features = false, features = ["read_core", "pe", "coff", "archive", "std"] } +windows-sys = "0.61.2" +blake3 = "1.8.7" +memchr = "2.8.3" +miniz_oxide = "0.9.1" +walkdir = "2.5.1" +tempfile = "3.27.0" + +[workspace.lints.rust] +unsafe_op_in_unsafe_fn = "deny" +unused_must_use = "deny" + +[workspace.lints.clippy] +all = { level = "warn", priority = -1 } +undocumented_unsafe_blocks = "warn" + +[profile.dev.package."*"] +# Dependencies (hashing, parsing) are hot paths when chewing through +# gigabytes of game data; keep them fast even in debug builds. +opt-level = 2 + +[profile.release] +debug = "line-tables-only" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..bd7598d --- /dev/null +++ b/README.md @@ -0,0 +1,43 @@ +# VIctory + +Runs Grand Theft Auto VI (Xbox Series X|S) natively on Windows, from files +the user supplies. + +> **Rule #1: nothing from the game is ever stored in this repository**: +> no assets, no code, nothing derived from them. Everything is built on the +> user's machine from the user's own files. See +> [docs/asset-policy.md](docs/asset-policy.md). + +The title's x86-64 code runs unchanged inside our process; VIctory supplies +the platform underneath it and converts the title's data, ahead of time where +it can and on first use where it must (shaders). See +[docs/architecture.md](docs/architecture.md). + +## Getting started + +Requirements: Windows 10/11 x64, a CPU with AVX2, Rust (pinned in +`rust-toolchain.toml`). + +```powershell +cargo xtask install-hooks # asset-policy check on every commit +copy victory.example.toml victory.toml # then set your paths (outside the repo) +cargo test --workspace # needs no game data +cargo run -p victory -- config # check your paths +``` + +## Commands + +``` +victory inspect [--imports] [--exports] +victory census [paths...] [--missing] [--strict] +victory lib-exports [--list] +victory shader-info [paths...] [--verbose] [--disasm] +victory run [--execute] [--unimplemented trap|zero] [--strict] +victory config +``` + +Logging: `VICTORY_LOG=victory_loader=trace,info`. + +## License + +GPL-3.0-or-later. See [LICENSE](LICENSE). diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml new file mode 100644 index 0000000..a005875 --- /dev/null +++ b/apps/victory/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "victory" +description = "Command-line front end: inspect, census, convert, run." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +victory-core.workspace = true +victory-pe.workspace = true +victory-loader.workspace = true +victory-hle.workspace = true +victory-shader.workspace = true +victory-game.workspace = true +anyhow.workspace = true +blake3.workspace = true +memchr.workspace = true +clap.workspace = true +walkdir.workspace = true + +[lints] +workspace = true diff --git a/apps/victory/src/census.rs b/apps/victory/src/census.rs new file mode 100644 index 0000000..469b8c5 --- /dev/null +++ b/apps/victory/src/census.rs @@ -0,0 +1,123 @@ +//! Which imports do titles need, and which do we cover? + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::Read; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use victory_hle::{HleResolver, HostPolicy}; +use victory_loader::Provenance; +use victory_pe::{ImageInfo, ImportSymbol}; + +#[derive(Default)] +struct DllStats { + functions: BTreeSet, + hle: usize, + host: usize, + missing: usize, + images: BTreeSet, +} + +pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> { + let paths = crate::default_paths(paths)?; + let resolver = HleResolver::new(if strict { + HostPolicy::none() + } else { + HostPolicy::default() + }); + + let mut images = 0usize; + let mut failed = Vec::new(); + let mut dlls: BTreeMap = BTreeMap::new(); + let mut missing: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); + + for root in &paths { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { + let path = entry.path(); + if !entry.file_type().is_file() || !looks_like_pe(path) { + continue; + } + let info = match std::fs::read(path) + .map_err(anyhow::Error::from) + .and_then(|d| ImageInfo::parse(&d).map_err(anyhow::Error::from)) + { + Ok(info) => info, + Err(e) => { + failed.push((path.to_path_buf(), e.to_string())); + continue; + } + }; + images += 1; + for module in info.imports.iter().chain(&info.delay_imports) { + let key = module.dll.to_ascii_lowercase(); + let stats = dlls.entry(key.clone()).or_default(); + stats.images.insert(path.to_path_buf()); + for e in &module.entries { + let class = resolver.classify(&module.dll, &e.symbol); + if class.is_none() { + missing + .entry((key.clone(), e.symbol.to_string())) + .or_default() + .insert(path.to_path_buf()); + } + // Count each dll!function once across all images. + if stats.functions.insert(e.symbol.clone()) { + match class { + Some(Provenance::Hle) => stats.hle += 1, + Some(Provenance::Host) => stats.host += 1, + None => stats.missing += 1, + } + } + } + } + } + } + + println!("{images} images scanned, {} unreadable", failed.len()); + for (p, e) in &failed { + println!(" skipped {}: {e}", p.display()); + } + println!( + "\n{:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", + "dll", "funcs", "hle", "host", "missing", "images" + ); + let (mut f, mut h, mut o, mut m) = (0, 0, 0, 0); + for (dll, s) in &dlls { + println!( + "{dll:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", + s.functions.len(), + s.hle, + s.host, + s.missing, + s.images.len() + ); + f += s.functions.len(); + h += s.hle; + o += s.host; + m += s.missing; + } + println!("{:<56} {f:>6} {h:>6} {o:>6} {m:>8}", "TOTAL"); + + if list_missing { + let mut rows: Vec<_> = missing.into_iter().collect(); + rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0))); + println!("\nmissing (by number of images using it)"); + for ((dll, sym), users) in rows { + println!(" {:>4} {dll}!{sym}", users.len()); + } + } + Ok(()) +} + +/// Cheap pre-filter: an `MZ` header, regardless of extension (console +/// packages do not always use .exe/.dll). +fn looks_like_pe(path: &Path) -> bool { + let mut magic = [0u8; 2]; + std::fs::File::open(path) + .and_then(|mut f| f.read_exact(&mut magic)) + .is_ok() + && &magic == b"MZ" +} diff --git a/apps/victory/src/inspect.rs b/apps/victory/src/inspect.rs new file mode 100644 index 0000000..3991d70 --- /dev/null +++ b/apps/victory/src/inspect.rs @@ -0,0 +1,153 @@ +use std::collections::BTreeMap; +use std::path::Path; + +use anyhow::{Context, Result}; +use victory_pe::implib::ImportLibrary; +use victory_pe::{ImageInfo, layout}; + +pub fn run(file: &Path, list_imports: bool, list_exports: bool) -> Result<()> { + let data = std::fs::read(file).with_context(|| format!("reading {}", file.display()))?; + let info = ImageInfo::parse(&data).with_context(|| format!("parsing {}", file.display()))?; + + println!("file {}", file.display()); + println!("blake3 {}", blake3::hash(&data).to_hex()); + if let Some(cv) = &info.codeview { + println!("pdb {} (key {})", cv.pdb_path, cv.symbol_key()); + } + println!( + "kind {}", + if info.is_dll() { "dll" } else { "exe" } + ); + println!( + "subsystem {} ({})", + info.subsystem, + info.subsystem_name() + ); + println!( + "image base {:#x} size {:#x}", + info.image_base, info.size_of_image + ); + println!("entry rva {:#x}", info.entry_rva); + println!( + "stack reserve {:#x} commit {:#x}", + info.stack_reserve, info.stack_commit + ); + println!( + "dll flags {:#06x}{}", + info.dll_characteristics, + dll_flags(info.dll_characteristics) + ); + println!( + "relocations {} exception table {} load config {}", + yes(info.has_relocations), + yes(info.has_exception_table), + yes(info.has_load_config) + ); + if let Some(tls) = &info.tls { + println!("tls {} callback(s)", tls.callback_rvas.len()); + } + + println!("\nsections"); + for s in &info.sections { + println!( + " {:<8} rva {:#010x} vsize {:#010x} raw {:#010x} flags {:#010x}", + s.name.trim_end_matches('\0'), + s.rva, + s.virtual_size, + s.file_size, + s.characteristics + ); + } + + println!( + "\nimports {} functions from {} DLLs", + info.import_count(), + info.imports.len() + ); + for m in &info.imports { + println!(" {:<48} {:>5}", m.dll, m.entries.len()); + if list_imports { + for e in &m.entries { + println!(" {}", e.symbol); + } + } + } + if !info.delay_imports.is_empty() { + println!("\ndelay-load imports"); + for m in &info.delay_imports { + println!(" {:<48} {:>5}", m.dll, m.entries.len()); + if list_imports { + for e in &m.entries { + println!(" {}", e.symbol); + } + } + } + } + + println!("\nexports {}", info.exports.len()); + if list_exports { + for e in &info.exports { + let name = e.name.as_deref().unwrap_or("(by ordinal)"); + match (&e.rva, &e.forward) { + (_, Some(fwd)) => println!(" {:>5} {name} -> {fwd}", e.ordinal), + (Some(rva), _) => println!(" {:>5} {name} {rva:#x}", e.ordinal), + _ => println!(" {:>5} {name}", e.ordinal), + } + } + } + Ok(()) +} + +pub fn lib_exports(lib: &Path, list: bool) -> Result<()> { + let data = std::fs::read(lib).with_context(|| format!("reading {}", lib.display()))?; + let parsed = + ImportLibrary::parse(&data).with_context(|| format!("parsing {}", lib.display()))?; + let mut by_dll: BTreeMap> = BTreeMap::new(); + for i in &parsed.imports { + by_dll + .entry(i.dll.to_ascii_lowercase()) + .or_default() + .push(i.export.to_string()); + } + println!( + "{} exports from {} DLLs ({} other members)", + parsed.imports.len(), + by_dll.len(), + parsed.other_members + ); + for (dll, names) in &by_dll { + println!("{dll:<60} {:>5}", names.len()); + if list { + for n in names { + println!(" {n}"); + } + } + } + Ok(()) +} + +fn yes(b: bool) -> &'static str { + if b { "yes" } else { "no" } +} + +fn dll_flags(v: u16) -> String { + use layout::dll_flags::*; + let names = [ + (HIGH_ENTROPY_VA, "high-entropy-va"), + (DYNAMIC_BASE, "dynamic-base"), + (FORCE_INTEGRITY, "force-integrity"), + (NX_COMPAT, "nx"), + (APPCONTAINER, "appcontainer"), + (GUARD_CF, "cfg"), + ]; + let set: Vec<_> = names + .iter() + .filter(|(f, _)| v & f != 0) + .map(|(_, n)| *n) + .collect(); + if set.is_empty() { + String::new() + } else { + format!(" ({})", set.join(", ")) + } +} diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs new file mode 100644 index 0000000..37c7a70 --- /dev/null +++ b/apps/victory/src/main.rs @@ -0,0 +1,165 @@ +//! `victory`: the command-line front end. +//! +//! Every command reads the user's own files and writes only to stdout or to +//! the user's cache directory (outside the repository). + +mod census; +mod inspect; +mod run; +mod shader; + +use std::path::PathBuf; + +use anyhow::Result; +use clap::{Parser, Subcommand, ValueEnum}; + +#[derive(Parser)] +#[command( + name = "victory", + version, + about = "Run an Xbox Series title natively on Windows" +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Summarise one PE image: headers, sections, imports, TLS, build id. + Inspect { + file: PathBuf, + /// List every imported function. + #[arg(long)] + imports: bool, + /// List every exported function. + #[arg(long)] + exports: bool, + }, + /// Aggregate the imports of every PE image under the given paths and + /// show which ones our runtime covers. Defaults to the configured + /// game and test-title directories. + Census { + paths: Vec, + /// Do not count host pass-through as covered. + #[arg(long)] + strict: bool, + /// List every missing `dll!function`, most used first. + #[arg(long)] + missing: bool, + }, + /// List the `dll!export` pairs an import library describes. + LibExports { + lib: PathBuf, + /// List every export, not just per-DLL counts. + #[arg(long)] + list: bool, + }, + /// Find shader containers in files or directories (also inside engine + /// archives, if uncompressed) and report their layout. + ShaderInfo { + paths: Vec, + /// Print one line per container found. + #[arg(long)] + verbose: bool, + /// Also list the decoded native instructions (implies --verbose). + #[arg(long)] + disasm: bool, + }, + /// Prepare, map and bind a title executable; with --execute, run it. + Run { + exe: PathBuf, + /// What unimplemented imports do when called. + #[arg(long, value_enum, default_value_t = Unimplemented::Trap)] + unimplemented: Unimplemented, + /// Disable host pass-through (everything must be implemented by us). + #[arg(long)] + strict: bool, + /// Actually start the title. Without it, stop after binding. + #[arg(long)] + execute: bool, + }, + /// Show the resolved configuration and check it. + Config, +} + +#[derive(Clone, Copy, ValueEnum)] +enum Unimplemented { + Trap, + Zero, +} + +fn main() -> Result<()> { + victory_core::logging::init("info"); + let cli = Cli::parse(); + match cli.command { + Command::Inspect { + file, + imports, + exports, + } => inspect::run(&file, imports, exports), + Command::Census { + paths, + strict, + missing, + } => census::run(paths, strict, missing), + Command::LibExports { lib, list } => inspect::lib_exports(&lib, list), + Command::ShaderInfo { + paths, + verbose, + disasm, + } => shader::run(paths, verbose || disasm, disasm), + Command::Run { + exe, + unimplemented, + strict, + execute, + } => run::run(&exe, unimplemented, strict, execute), + Command::Config => show_config(), + } +} + +fn show_config() -> Result<()> { + let cfg = victory_core::Config::load()?; + let status = |p: &Option| match p { + Some(p) if p.exists() => format!("{}", p.display()), + Some(p) => format!("{} (does not exist)", p.display()), + None => "(not set)".to_owned(), + }; + println!( + "config file : {}", + cfg.source + .as_ref() + .map_or("(none)".into(), |p| p.display().to_string()) + ); + println!("game_dir : {}", status(&cfg.game_dir)); + println!("cache_dir : {}", cfg.cache_dir.display()); + for t in &cfg.test_titles { + println!("test_title : {}", status(&Some(t.clone()))); + } + for p in cfg + .game_dir + .iter() + .chain(&cfg.test_titles) + .chain([&cfg.cache_dir]) + { + if let Err(e) = victory_core::ensure_outside_repo(p) { + println!("POLICY VIOLATION: {e}"); + } + } + Ok(()) +} + +/// Paths given on the command line, or the configured game + test titles. +pub(crate) fn default_paths(paths: Vec) -> Result> { + if !paths.is_empty() { + return Ok(paths); + } + let cfg = victory_core::Config::load()?; + let all: Vec = cfg.game_dir.into_iter().chain(cfg.test_titles).collect(); + anyhow::ensure!( + !all.is_empty(), + "no paths given and none configured (see victory.example.toml)" + ); + Ok(all) +} diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs new file mode 100644 index 0000000..e90faf5 --- /dev/null +++ b/apps/victory/src/run.rs @@ -0,0 +1,64 @@ +use std::path::Path; + +use anyhow::{Context, Result}; + +use crate::Unimplemented; + +#[cfg(windows)] +pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool) -> Result<()> { + use std::sync::Arc; + use victory_hle::{HleResolver, HostPolicy}; + use victory_loader::UnimplementedPolicy; + + let cfg = victory_core::Config::load()?; + let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; + let prepared = victory_loader::prepare(&original)?; + let hash = prepared.original_hash.to_hex(); + match victory_game::identify(&hash) { + Some(build) => println!("build {} ({hash})", build.label), + None => println!("build unknown ({hash})"), + } + + let image = victory_loader::load(&prepared, &cfg.cache_subdir("images")?)?; + victory_hle::runtime::set_main_image(image.base()); + let resolver = HleResolver::new(if strict { + HostPolicy::none() + } else { + HostPolicy::default() + }); + let policy = match unimplemented { + Unimplemented::Trap => UnimplementedPolicy::Trap, + Unimplemented::Zero => UnimplementedPolicy::ReturnZero, + }; + let report = image.bind_imports(&resolver, policy)?; + println!( + "mapped at {:#x} (preferred {:#x})", + image.base(), + image.info().image_base + ); + println!( + "bound {} hle, {} host, {} missing", + report.hle, + report.host, + report.missing.len() + ); + for m in &report.missing { + println!(" missing {}!{}", m.dll, m.symbol); + } + if !execute { + println!("not executing (pass --execute to start the title)"); + return Ok(()); + } + // SAFETY: imports are bound; from here on we run title code. + let main = unsafe { Arc::new(image).spawn_main()? }; + let code = main + .join() + .map_err(|_| anyhow::anyhow!("title main thread panicked"))?; + println!("title exited with {code}"); + Ok(()) +} + +#[cfg(not(windows))] +pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool) -> Result<()> { + anyhow::bail!("running titles requires Windows") +} diff --git a/apps/victory/src/shader.rs b/apps/victory/src/shader.rs new file mode 100644 index 0000000..cbe8842 --- /dev/null +++ b/apps/victory/src/shader.rs @@ -0,0 +1,176 @@ +//! Survey shader containers: bitcode, console additions and native code. + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use anyhow::Result; +use victory_shader::gfx10::{self, Instruction}; +use victory_shader::{Container, DxilProgram, FourCC, HwStage, ShaderError, native_programs}; + +/// Files above this size are skipped (read whole into memory for now). +const MAX_FILE: u64 = 2 << 30; + +#[derive(Default)] +struct Totals { + containers: usize, + with_dxil_part: usize, + with_bitcode: usize, + standard_layout: usize, + xdat: usize, + xbop: usize, + kinds: BTreeMap, + with_native: usize, + native_stages: BTreeMap, + native_errors: BTreeMap, + decoded: usize, + instructions: usize, + unnamed: BTreeMap, + decode_errors: BTreeMap<&'static str, usize>, + files_with_shaders: usize, +} + +pub fn run(paths: Vec, verbose: bool, disasm: bool) -> Result<()> { + let paths = crate::default_paths(paths)?; + let mut t = Totals::default(); + for root in &paths { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { + if !entry.file_type().is_file() { + continue; + } + let path = entry.path(); + if entry.metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE { + eprintln!("skipping large file {}", path.display()); + continue; + } + let Ok(data) = std::fs::read(path) else { + continue; + }; + let mut found_here = 0; + for offset in memchr::memmem::find_iter(&data, b"DXBC") { + let Ok(container) = Container::parse(&data[offset..]) else { + continue; + }; + found_here += 1; + t.containers += 1; + let dxil = container.part(FourCC::DXIL); + t.with_dxil_part += usize::from(dxil.is_some()); + let program = dxil.and_then(|p| DxilProgram::parse(p.data).ok()); + let mut listing = Vec::new(); + // Independent of the bitcode: titles may strip it. + let native = match dxil.map(|p| native_programs(p.data)) { + Some(Ok(programs)) if !programs.is_empty() => { + t.with_native += 1; + let mut list = Vec::new(); + for n in &programs { + *t.native_stages.entry(n.stage).or_default() += 1; + list.push(format!("{:?} {} B", n.stage, n.code.len())); + match gfx10::decode(&n.code) { + Ok(insts) => { + t.decoded += 1; + t.instructions += insts.len(); + for i in insts.iter().filter(|i| i.name().is_none()) { + let key = format!("{:?} {:#x}", i.encoding, i.opcode); + *t.unnamed.entry(key).or_default() += 1; + } + if disasm { + listing.extend(insts.iter().map(format_instruction)); + } + } + Err(e) => { + let reason = match e { + ShaderError::Isa { reason, .. } => reason, + _ => "other", + }; + *t.decode_errors.entry(reason).or_default() += 1; + list.push(format!("({e})")); + } + } + } + format!(", native {}", list.join(" ")) + } + Some(Err(e)) => { + *t.native_errors.entry(e.to_string()).or_default() += 1; + format!(", native: {e}") + } + _ => String::new(), + }; + let line = match &program { + Some(p) => { + t.with_bitcode += 1; + let x = p.xbox_extras(); + t.standard_layout += usize::from(p.is_standard_layout()); + t.xdat += usize::from(x.xdat); + t.xbop += usize::from(x.xbop); + *t.kinds.entry(format!("{:?}", p.kind)).or_default() += 1; + format!( + "{:?} sm{}.{} bitcode {} B, xdat {}, xbop {}", + p.kind, + p.shader_model.0, + p.shader_model.1, + p.bitcode.len(), + x.xdat, + x.xbop + ) + } + None => "no parsable DXIL program".to_owned(), + } + &native; + if verbose { + println!("{}@{offset:#x}: {line}", path.display()); + for l in &listing { + println!("{l}"); + } + } + } + t.files_with_shaders += usize::from(found_here > 0); + } + } + println!( + "containers found {} (in {} files)", + t.containers, t.files_with_shaders + ); + println!(" with DXIL part {}", t.with_dxil_part); + println!(" with LLVM bitcode {}", t.with_bitcode); + println!(" PC-standard layout {}", t.standard_layout); + println!(" XDAT prefix {}", t.xdat); + println!(" xbop trailer {}", t.xbop); + for (k, n) in &t.kinds { + println!(" {k:<20} {n}"); + } + println!(" with native code {}", t.with_native); + for (stage, n) in &t.native_stages { + println!(" {:<18} {n}", format!("{stage:?}")); + } + for (e, n) in &t.native_errors { + println!(" native unreadable {n}: {e}"); + } + if t.with_native > 0 { + println!( + " decoded programs {} ({} instructions)", + t.decoded, t.instructions + ); + for (e, n) in &t.decode_errors { + println!(" decode failed {n}: {e}"); + } + let mut unnamed: Vec<_> = t.unnamed.iter().collect(); + unnamed.sort_by_key(|&(_, n)| std::cmp::Reverse(*n)); + for (op, n) in unnamed.iter().take(10) { + println!(" opcode not in table {op} x{n}"); + } + } + if t.containers == 0 { + println!("(none found: shaders may sit in compressed or encrypted archives)"); + } + Ok(()) +} + +fn format_instruction(i: &Instruction) -> String { + let words: Vec<_> = i.words.iter().map(|w| format!("{w:08X}")).collect(); + let name = match i.name() { + Some(n) => n.to_owned(), + None => format!("<{:?} {:#x}>", i.encoding, i.opcode), + }; + format!(" {:06x}: {:<44} {name}", i.offset, words.join(" ")) +} diff --git a/crates/victory-core/Cargo.toml b/crates/victory-core/Cargo.toml new file mode 100644 index 0000000..a235609 --- /dev/null +++ b/crates/victory-core/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "victory-core" +description = "Shared plumbing: configuration, paths, the asset-policy guard, logging." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +anyhow.workspace = true +thiserror.workspace = true +serde.workspace = true +toml.workspace = true +tracing-subscriber.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs new file mode 100644 index 0000000..c412f9b --- /dev/null +++ b/crates/victory-core/src/config.rs @@ -0,0 +1,166 @@ +//! Where the user's files live. +//! +//! Resolution order for each value: environment variable, then the config +//! file (`VICTORY_CONFIG`, else `./victory.toml`), then the default. +//! See `victory.example.toml` at the repository root. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use serde::Deserialize; + +use crate::policy::ensure_outside_repo; + +#[derive(Debug, Default, Clone)] +pub struct Config { + /// The user's dump of Grand Theft Auto VI. + pub game_dir: Option, + /// Root for all derived data. Always outside the repository. + pub cache_dir: PathBuf, + /// Other titles used to exercise platform-level code. + pub test_titles: Vec, + /// The config file that was read, if any. + pub source: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct FileConfig { + #[serde(default)] + paths: FilePaths, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct FilePaths { + game_dir: Option, + cache_dir: Option, + #[serde(default)] + test_titles: Vec, +} + +impl Config { + /// Loads configuration from the environment and the config file. + pub fn load() -> Result { + let explicit = std::env::var_os("VICTORY_CONFIG").map(PathBuf::from); + let path = explicit + .clone() + .unwrap_or_else(|| PathBuf::from("victory.toml")); + let file = if path.is_file() { + let text = std::fs::read_to_string(&path) + .with_context(|| format!("reading {}", path.display()))?; + Some((path, text)) + } else if let Some(p) = explicit { + anyhow::bail!( + "VICTORY_CONFIG points at {}, which does not exist", + p.display() + ); + } else { + None + }; + let (source, parsed) = match file { + Some((path, text)) => { + let parsed: FileConfig = + toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; + (Some(path), parsed) + } + None => (None, FileConfig::default()), + }; + Self::resolve(parsed.paths, source, |k| std::env::var_os(k)) + } + + fn resolve( + file: FilePaths, + source: Option, + env: impl Fn(&str) -> Option, + ) -> Result { + let env_path = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from); + let test_titles = match env("VICTORY_TEST_TITLES") { + Some(v) => std::env::split_paths(&v) + .filter(|p| !p.as_os_str().is_empty()) + .collect(), + None => file.test_titles, + }; + let cache_dir = env_path("VICTORY_CACHE_DIR") + .or(file.cache_dir) + .map_or_else(default_cache_dir, Ok)?; + Ok(Config { + game_dir: env_path("VICTORY_GAME_DIR").or(file.game_dir), + cache_dir, + test_titles, + source, + }) + } + + /// The game directory, or a helpful error if it is not configured. + pub fn require_game_dir(&self) -> Result<&Path> { + self.game_dir.as_deref().context( + "no game directory configured: set VICTORY_GAME_DIR or [paths].game_dir in \ + victory.toml (see victory.example.toml)", + ) + } + + /// Returns `/`, creating it, after checking the asset policy. + pub fn cache_subdir(&self, sub: &str) -> Result { + let dir = self.cache_dir.join(sub); + ensure_outside_repo(&dir)?; + std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?; + Ok(dir) + } +} + +fn default_cache_dir() -> Result { + let base = std::env::var_os("LOCALAPPDATA") + .or_else(|| std::env::var_os("XDG_CACHE_HOME")) + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))) + .context("cannot determine a cache directory; set VICTORY_CACHE_DIR")?; + Ok(base.join("victory").join("cache")) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsString; + + #[test] + fn environment_overrides_file() { + let file = FilePaths { + game_dir: Some("from-file".into()), + cache_dir: Some("cache-from-file".into()), + ..Default::default() + }; + let env = |k: &str| (k == "VICTORY_GAME_DIR").then(|| OsString::from("from-env")); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-env")); + assert_eq!(cfg.cache_dir, PathBuf::from("cache-from-file")); + } + + #[test] + fn empty_env_values_are_ignored() { + let file = FilePaths { + game_dir: Some("from-file".into()), + ..Default::default() + }; + let env = |k: &str| (k == "VICTORY_GAME_DIR").then(OsString::new); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-file")); + } + + #[test] + fn example_config_parses() { + let text = include_str!("../../../victory.example.toml"); + let parsed: FileConfig = toml::from_str(text).unwrap(); + assert!(parsed.paths.game_dir.is_some()); + } + + #[test] + fn cache_inside_repo_is_refused() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache"); + let cfg = Config { + cache_dir: inside, + ..Default::default() + }; + assert!(cfg.cache_subdir("x").is_err()); + } +} diff --git a/crates/victory-core/src/lib.rs b/crates/victory-core/src/lib.rs new file mode 100644 index 0000000..011df7e --- /dev/null +++ b/crates/victory-core/src/lib.rs @@ -0,0 +1,13 @@ +//! Shared plumbing for every VIctory crate and tool. +//! +//! * [`config`]: where the user's files live (never inside the repository). +//! * [`policy`]: the runtime half of rule #1, refusing to write +//! game-derived data into the source tree. +//! * [`logging`]: one tracing setup for all binaries. + +pub mod config; +pub mod logging; +pub mod policy; + +pub use config::Config; +pub use policy::{PolicyError, ensure_outside_repo}; diff --git a/crates/victory-core/src/logging.rs b/crates/victory-core/src/logging.rs new file mode 100644 index 0000000..33388fb --- /dev/null +++ b/crates/victory-core/src/logging.rs @@ -0,0 +1,19 @@ +//! One tracing setup for every binary. +//! +//! Filter with `VICTORY_LOG` (falls back to `RUST_LOG`), e.g. +//! `VICTORY_LOG=victory_loader=trace,info`. + +use tracing_subscriber::EnvFilter; + +pub fn init(default_level: &str) { + let filter = std::env::var("VICTORY_LOG") + .or_else(|_| std::env::var("RUST_LOG")) + .ok() + .and_then(|v| EnvFilter::try_new(v).ok()) + .unwrap_or_else(|| EnvFilter::new(default_level)); + let _ = tracing_subscriber::fmt() + .with_env_filter(filter) + .with_target(true) + .with_writer(std::io::stderr) + .try_init(); +} diff --git a/crates/victory-core/src/policy.rs b/crates/victory-core/src/policy.rs new file mode 100644 index 0000000..b10e1c6 --- /dev/null +++ b/crates/victory-core/src/policy.rs @@ -0,0 +1,159 @@ +//! Rule #1, enforced at runtime: game-derived data never lands in the repo. +//! +//! Everything VIctory produces from the user's files (converted assets, +//! prepared images, shader caches, crash dumps) is as much "from the game" +//! as the files themselves. Every tool that writes such output must call +//! [`ensure_outside_repo`] on the destination first. The static half of the +//! rule is `cargo xtask policy`, which checks what git tracks. + +use std::path::{Component, Path, PathBuf}; + +/// Marker file at the root of the source tree. +pub const ROOT_MARKER: &str = ".victory-root"; + +/// The source tree this binary was compiled from. +fn compiled_workspace_root() -> PathBuf { + // crates/victory-core -> workspace root + Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") +} + +#[derive(Debug, thiserror::Error)] +pub enum PolicyError { + #[error( + "refusing to use {path} for game-derived data: it is inside the VIctory source tree \ + ({root}). Keep game files, caches and outputs outside the repository \ + (see docs/asset-policy.md)" + )] + InsideRepo { path: PathBuf, root: PathBuf }, + #[error("cannot resolve {path}: {source}")] + Io { + path: PathBuf, + source: std::io::Error, + }, +} + +/// Returns `Ok` only if `path` is outside every VIctory source tree. +/// +/// `path` does not have to exist yet. Two checks are made: +/// 1. it is not below the source tree this binary was built from; +/// 2. none of its ancestors contains the [`ROOT_MARKER`] file (catches +/// other clones/copies of the repository). +pub fn ensure_outside_repo(path: &Path) -> Result<(), PolicyError> { + let resolved = resolve(path)?; + + if let Ok(root) = std::fs::canonicalize(compiled_workspace_root()) + && root.join(ROOT_MARKER).is_file() + && resolved.starts_with(&root) + { + return Err(PolicyError::InsideRepo { + path: path.to_path_buf(), + root, + }); + } + + for ancestor in resolved.ancestors() { + if ancestor.join(ROOT_MARKER).is_file() { + return Err(PolicyError::InsideRepo { + path: path.to_path_buf(), + root: ancestor.to_path_buf(), + }); + } + } + Ok(()) +} + +/// Canonicalizes the longest existing prefix of `path` and re-appends the +/// rest, so that paths which do not exist yet can still be compared. +fn resolve(path: &Path) -> Result { + let absolute = if path.is_absolute() { + path.to_path_buf() + } else { + std::env::current_dir() + .map_err(|source| PolicyError::Io { + path: path.to_path_buf(), + source, + })? + .join(path) + }; + + let mut existing = absolute.as_path(); + let mut rest = Vec::new(); + loop { + match std::fs::canonicalize(existing) { + Ok(canon) => { + let mut out = canon; + for component in rest.iter().rev() { + out.push(component); + } + return Ok(normalize(&out)); + } + Err(source) => match (existing.parent(), existing.file_name()) { + (Some(parent), Some(name)) => { + rest.push(name.to_os_string()); + existing = parent; + } + _ => { + return Err(PolicyError::Io { + path: path.to_path_buf(), + source, + }); + } + }, + } + } +} + +/// Removes `.` and resolves `..` lexically (only used on the non-existing tail). +fn normalize(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + out.pop(); + } + c => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_paths_inside_this_repo() { + let inside = compiled_workspace_root().join("cache").join("textures"); + assert!(matches!( + ensure_outside_repo(&inside), + Err(PolicyError::InsideRepo { .. }) + )); + let sneaky = std::env::temp_dir().join("..").join("x"); // sanity: no panic + let _ = ensure_outside_repo(&sneaky); + } + + #[test] + fn rejects_dotdot_escapes_back_into_repo() { + let root = compiled_workspace_root(); + let path = root + .join("crates") + .join("..") + .join("not-yet-created") + .join("out"); + assert!(ensure_outside_repo(&path).is_err()); + } + + #[test] + fn rejects_other_clones_via_marker() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join(ROOT_MARKER), "").unwrap(); + assert!(ensure_outside_repo(&tmp.path().join("cache")).is_err()); + } + + #[test] + fn accepts_unrelated_directories() { + let tmp = tempfile::tempdir().unwrap(); + ensure_outside_repo(&tmp.path().join("does").join("not").join("exist")).unwrap(); + } +} diff --git a/crates/victory-formats/Cargo.toml b/crates/victory-formats/Cargo.toml new file mode 100644 index 0000000..6f3efd9 --- /dev/null +++ b/crates/victory-formats/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "victory-formats" +description = "Platform-level data formats: texture layouts, compressed textures, audio codecs." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-formats/src/lib.rs b/crates/victory-formats/src/lib.rs new file mode 100644 index 0000000..43c4345 --- /dev/null +++ b/crates/victory-formats/src/lib.rs @@ -0,0 +1,6 @@ +//! Platform-level data formats, shared by every Xbox Series title. +//! +//! Planned modules, each pure (bytes in, bytes out, no I/O): texture +//! layouts (RDNA2 swizzle modes to linear), BCPack textures, audio codecs +//! (XMA2, Opus), and the zlib streams used by hardware decompression. +//! Which come first depends on what Grand Theft Auto VI's assets contain. diff --git a/crates/victory-game/Cargo.toml b/crates/victory-game/Cargo.toml new file mode 100644 index 0000000..8fc1fae --- /dev/null +++ b/crates/victory-game/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "victory-game" +description = "Everything specific to Grand Theft Auto VI: its containers, build identities, patches." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-game/src/lib.rs b/crates/victory-game/src/lib.rs new file mode 100644 index 0000000..646c6f7 --- /dev/null +++ b/crates/victory-game/src/lib.rs @@ -0,0 +1,23 @@ +//! Everything specific to Grand Theft Auto VI: its container formats, build +//! identities, and the hooks we place in its code (located by per-build +//! offsets or byte-pattern signatures). What may and may not be stored here +//! is defined in docs/asset-policy.md. + +/// A specific build of the Grand Theft Auto VI executable we know how to run. +#[derive(Debug, Clone, Copy)] +pub struct KnownBuild { + /// Our own label, e.g. "1.0.0 retail". + pub label: &'static str, + /// BLAKE3 of the original executable, hex. + pub blake3: &'static str, +} + +/// Builds we support. Empty until the executable is available. +pub const KNOWN_BUILDS: &[KnownBuild] = &[]; + +/// Looks up a build by the BLAKE3 hash of its executable. +pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> { + KNOWN_BUILDS + .iter() + .find(|b| b.blake3.eq_ignore_ascii_case(blake3_hex)) +} diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml new file mode 100644 index 0000000..d45e5bd --- /dev/null +++ b/crates/victory-gpu/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "victory-gpu" +description = "D3D12.X command streams and GPU memory, translated onto host D3D12." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs new file mode 100644 index 0000000..bbe28a7 --- /dev/null +++ b/crates/victory-gpu/src/lib.rs @@ -0,0 +1,12 @@ +//! D3D12.X on host D3D12. +//! +//! D3D12.X records many commands by writing command-processor packets into +//! command lists from code inlined into the title itself, so no import-level +//! hook sees them. This crate decodes those packet streams at +//! `ExecuteCommandLists` time and replays them on host D3D12, and maps the +//! title's GPU virtual addresses (console memory is unified) to host +//! resources. +//! +//! Planned modules: `packets` (stream decoder), `memory` (title GPU +//! addresses to host heaps), `pipeline` (PSOs from `victory-shader` output), +//! `present` (swap chain, frame pacing). diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml new file mode 100644 index 0000000..fd0d2a5 --- /dev/null +++ b/crates/victory-hle/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "victory-hle" +description = "Our implementation of the Xbox system API surface the title imports." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +victory-loader.workspace = true +victory-pe.workspace = true +tracing.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = [ + "Win32_Foundation", + "Win32_System_LibraryLoader", +] } + +[dev-dependencies] +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs new file mode 100644 index 0000000..904d5e0 --- /dev/null +++ b/crates/victory-hle/src/host.rs @@ -0,0 +1,123 @@ +//! Pass-through to the host's own implementation of shared APIs. + +use victory_pe::ImportSymbol; + +/// Which DLLs may be satisfied by the host's own implementation. +/// +/// Console titles link mostly against Windows API sets that behave the same +/// on PC. Passing those through lets bring-up focus on what really differs. +/// Anything whose semantics differ on console (memory, files, threads) is +/// overridden in `modules`, which always wins over the host. +#[derive(Debug, Clone)] +pub struct HostPolicy { + /// Lower-case patterns; a trailing `*` matches a prefix. + pub allow: Vec, +} + +impl Default for HostPolicy { + fn default() -> Self { + let allow = [ + "api-ms-win-core-*", + "api-ms-win-eventing-*", + "api-ms-win-security-*", + "api-ms-win-crt-*", + "kernel32.dll", + "kernelbase.dll", + "ntdll.dll", + "ucrtbase.dll", + "vcruntime140*", + "msvcp140*", + "ws2_32.dll", + "bcrypt.dll", + "crypt32.dll", + "ncrypt.dll", + "winhttp.dll", + "dnsapi.dll", + "sspicli.dll", + "cabinet.dll", + "avrt.dll", + ]; + HostPolicy { + allow: allow.iter().map(|s| s.to_string()).collect(), + } + } +} + +impl HostPolicy { + /// No pass-through at all: shows the full surface a title needs. + pub fn none() -> Self { + HostPolicy { allow: Vec::new() } + } + + pub fn allows(&self, dll: &str) -> bool { + let dll = dll.to_ascii_lowercase(); + self.allow + .iter() + .any(|pattern| match pattern.strip_suffix('*') { + Some(prefix) => dll.starts_with(prefix), + None => dll == *pattern, + }) + } + + pub(crate) fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Option { + if !self.allows(dll) { + return None; + } + imp::resolve(dll, symbol) + } +} + +#[cfg(windows)] +mod imp { + use std::collections::HashMap; + use std::ffi::CString; + use std::sync::{LazyLock, Mutex}; + + use victory_pe::ImportSymbol; + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA, + }; + + /// Module handles by lower-case DLL name (stored as usize: Send + Sync). + static MODULES: LazyLock>> = LazyLock::new(Default::default); + + pub(super) fn resolve(dll: &str, symbol: &ImportSymbol) -> Option { + let module = module(dll)?; + let proc = match symbol { + ImportSymbol::Name { name, .. } => { + let name = CString::new(name.as_str()).ok()?; + // SAFETY: valid module handle, NUL-terminated name. + unsafe { GetProcAddress(module as _, name.as_ptr().cast()) } + } + // SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module. + ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(module as _, *o as usize as _) }, + }; + proc.map(|f| f as *const () as usize) + } + + fn module(dll: &str) -> Option { + let key = dll.to_ascii_lowercase(); + let mut cache = MODULES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&m) = cache.get(&key) { + return Some(m); + } + let name = CString::new(key.as_str()).ok()?; + // System32 only: never pick up a same-named DLL from the current folder or PATH. + // SAFETY: NUL-terminated DLL name; only allow-listed system DLLs get here. + let handle = unsafe { + LoadLibraryExA( + name.as_ptr().cast(), + std::ptr::null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + } as usize; + (handle != 0).then(|| *cache.entry(key).or_insert(handle)) + } +} + +#[cfg(not(windows))] +mod imp { + pub(super) fn resolve(_dll: &str, _symbol: &victory_pe::ImportSymbol) -> Option { + None + } +} diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs new file mode 100644 index 0000000..a231331 --- /dev/null +++ b/crates/victory-hle/src/lib.rs @@ -0,0 +1,120 @@ +//! Our implementation of the Xbox system API surface. +//! +//! A title imports from three kinds of DLLs, and each gets its own policy: +//! +//! | kind | examples | handled by | +//! |------|----------|------------| +//! | Windows API sets the console shares with PC | `api-ms-win-core-synch-*`, `ws2_32.dll` | host pass-through, overridden here where console behaviour differs (paths, memory) | +//! | console-only system APIs | `xgameruntime.dll`, `xmem.dll`, `d3d12_xs.dll` | implemented here, in [`modules`] | +//! | anything else | | an unimplemented-import stub from the loader | +//! +//! Resolution order for every import: an implementation in [`modules`], +//! then the host if [`HostPolicy`] allows that DLL, then `Missing`. + +mod host; +pub mod modules; +mod registry; +pub mod runtime; + +pub use host::HostPolicy; +pub use registry::{HleExport, HleModule, registry}; + +use victory_loader::{ImportResolver, Provenance, Resolution}; +use victory_pe::ImportSymbol; + +/// Resolves a title's imports against our runtime and the host. +#[derive(Debug, Default)] +pub struct HleResolver { + pub host: HostPolicy, +} + +impl HleResolver { + pub fn new(host: HostPolicy) -> Self { + HleResolver { host } + } + + /// Where an import would come from, without binding anything. + pub fn classify(&self, dll: &str, symbol: &ImportSymbol) -> Option { + match self.resolve(dll, symbol) { + Resolution::Found { provenance, .. } => Some(provenance), + Resolution::Missing => None, + } + } +} + +impl ImportResolver for HleResolver { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + if let ImportSymbol::Name { name, .. } = symbol + && let Some(address) = registry::lookup(dll, name) + { + return Resolution::Found { + address, + provenance: Provenance::Hle, + }; + } + match self.host.resolve(dll, symbol) { + Some(address) => Resolution::Found { + address, + provenance: Provenance::Host, + }, + None => Resolution::Missing, + } + } +} + +// The registry is code-only, so the "Missing" outcome can be checked on any +// host; host pass-through itself needs Windows. +#[cfg(test)] +mod tests { + use super::*; + + fn name(n: &str) -> ImportSymbol { + ImportSymbol::Name { + hint: 0, + name: n.into(), + } + } + + #[test] + fn console_api_resolves_to_hle() { + let r = HleResolver::new(HostPolicy::none()); + assert_eq!( + r.classify("XGameRuntime.dll", &name("XGameRuntimeInitialize")), + Some(Provenance::Hle) + ); + } + + #[test] + fn strict_policy_reports_missing() { + let r = HleResolver::new(HostPolicy::none()); + assert_eq!( + r.classify("api-ms-win-core-synch-l1-1-0.dll", &name("Sleep")), + None + ); + } + + #[cfg(windows)] + #[test] + fn shared_api_sets_pass_through_to_host() { + let r = HleResolver::default(); + assert_eq!( + r.classify("api-ms-win-core-synch-l1-2-0.dll", &name("Sleep")), + Some(Provenance::Host) + ); + // Console-only DLLs never pass through. + assert_eq!(r.classify("xmem.dll", &name("XMemAllocDefault")), None); + } + + #[cfg(windows)] + #[test] + fn overrides_win_over_host() { + let r = HleResolver::default(); + assert_eq!( + r.classify( + "api-ms-win-core-libraryloader-l1-2-0.dll", + &name("GetModuleHandleW") + ), + Some(Provenance::Hle) + ); + } +} diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs new file mode 100644 index 0000000..c3faa3e --- /dev/null +++ b/crates/victory-hle/src/modules/kernel.rs @@ -0,0 +1,65 @@ +//! Overrides of shared Windows APIs whose console meaning differs. +//! +//! Only the differences live here; everything else passes through to the +//! host (see `HostPolicy`). +#![allow(non_snake_case)] + +use std::ffi::c_void; + +use crate::{HleModule, hle_export, runtime}; + +/// `GetModuleHandleW(NULL)` must return the title's image, not our exe. +pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void { + if name.is_null() { + return runtime::main_image().unwrap_or(0) as *mut c_void; + } + host::get_module_handle_w(name) +} + +/// `GetModuleHandleA(NULL)` must return the title's image, not our exe. +pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void { + if name.is_null() { + return runtime::main_image().unwrap_or(0) as *mut c_void; + } + host::get_module_handle_a(name) +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "kernel", + dlls: &[ + "kernel32.dll", + "kernelbase.dll", + "api-ms-win-core-libraryloader-*", + ], + exports: vec![hle_export!(GetModuleHandleW), hle_export!(GetModuleHandleA)], + } +} + +#[cfg(windows)] +mod host { + use std::ffi::c_void; + + pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void { + // SAFETY: forwarding the title's own argument to the host API. + unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(name) } + } + + pub(super) fn get_module_handle_a(name: *const u8) -> *mut c_void { + // SAFETY: forwarding the title's own argument to the host API. + unsafe { windows_sys::Win32::System::LibraryLoader::GetModuleHandleA(name) } + } +} + +#[cfg(not(windows))] +mod host { + use std::ffi::c_void; + + pub(super) fn get_module_handle_w(_: *const u16) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn get_module_handle_a(_: *const u8) -> *mut c_void { + std::ptr::null_mut() + } +} diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs new file mode 100644 index 0000000..0d0f47b --- /dev/null +++ b/crates/victory-hle/src/modules/mod.rs @@ -0,0 +1,19 @@ +//! Implementations, one module per area of the console API. +//! +//! Adding an API: write an `extern "system"` function named exactly like +//! the import, then list it with `hle_export!` in the module's `module()`. +//! Run `victory census` over your titles to see what is still missing. +//! +//! Planned areas (driven by census results, not by completeness): +//! `xmem` (console memory types, GPU-visible allocations), `file` (package +//! paths), `thread` (TLS callbacks for title threads), `d3d12x` (bridge to +//! `victory-gpu`), `xaudio2`, `gameinput`, `xuser`/`xstore` stubs. + +pub mod kernel; +pub mod xgameruntime; + +use crate::HleModule; + +pub(crate) fn all() -> Vec { + vec![kernel::module(), xgameruntime::module()] +} diff --git a/crates/victory-hle/src/modules/xgameruntime.rs b/crates/victory-hle/src/modules/xgameruntime.rs new file mode 100644 index 0000000..01ed816 --- /dev/null +++ b/crates/victory-hle/src/modules/xgameruntime.rs @@ -0,0 +1,30 @@ +//! `xgameruntime.dll`: the console game runtime (XGame*, XUser*, XTaskQueue*...). +//! +//! The DLL names titles actually import these from are confirmed by running +//! `victory census` on real titles; extend `dlls` accordingly. +#![allow(non_snake_case)] + +use crate::{HleModule, hle_export}; + +pub type HRESULT = i32; +pub const S_OK: HRESULT = 0; + +pub extern "system" fn XGameRuntimeInitialize() -> HRESULT { + tracing::info!("XGameRuntimeInitialize"); + S_OK +} + +pub extern "system" fn XGameRuntimeUninitialize() { + tracing::info!("XGameRuntimeUninitialize"); +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "xgameruntime", + dlls: &["xgameruntime.dll"], + exports: vec![ + hle_export!(XGameRuntimeInitialize), + hle_export!(XGameRuntimeUninitialize), + ], + } +} diff --git a/crates/victory-hle/src/registry.rs b/crates/victory-hle/src/registry.rs new file mode 100644 index 0000000..563e7b0 --- /dev/null +++ b/crates/victory-hle/src/registry.rs @@ -0,0 +1,94 @@ +//! The table of everything we implement. + +use std::sync::LazyLock; + +use crate::modules; + +/// One function we implement, under the name the title imports. +#[derive(Debug, Clone, Copy)] +pub struct HleExport { + pub name: &'static str, + pub address: usize, +} + +/// A group of implementations and the DLL names they answer for. +#[derive(Debug)] +pub struct HleModule { + /// Human-readable name, e.g. "kernel". + pub name: &'static str, + /// Lower-case DLL names served. A trailing `*` matches a prefix, which + /// covers versioned API sets (`api-ms-win-core-libraryloader-l1-2-0.dll`). + pub dlls: &'static [&'static str], + pub exports: Vec, +} + +impl HleModule { + pub fn serves(&self, dll: &str) -> bool { + let dll = dll.to_ascii_lowercase(); + self.dlls + .iter() + .any(|pattern| match pattern.strip_suffix('*') { + Some(prefix) => dll.starts_with(prefix), + None => dll == *pattern, + }) + } +} + +/// Declares an export whose Rust name equals the imported name. +#[macro_export] +macro_rules! hle_export { + ($f:ident) => { + $crate::HleExport { + name: stringify!($f), + address: $f as *const () as usize, + } + }; +} + +static REGISTRY: LazyLock> = LazyLock::new(modules::all); + +/// All modules we implement. +pub fn registry() -> &'static [HleModule] { + ®ISTRY +} + +pub(crate) fn lookup(dll: &str, name: &str) -> Option { + registry() + .iter() + .filter(|m| m.serves(dll)) + .flat_map(|m| m.exports.iter()) + .find(|e| e.name == name) + .map(|e| e.address) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn export_names_are_unique_per_dll_pattern() { + for module in registry() { + let mut names: Vec<_> = module.exports.iter().map(|e| e.name).collect(); + names.sort_unstable(); + let before = names.len(); + names.dedup(); + assert_eq!( + before, + names.len(), + "duplicate export in module {}", + module.name + ); + } + } + + #[test] + fn api_set_prefix_matching() { + let m = HleModule { + name: "t", + dlls: &["api-ms-win-core-libraryloader-*"], + exports: vec![], + }; + assert!(m.serves("API-MS-WIN-CORE-LIBRARYLOADER-L1-2-0.dll")); + assert!(!m.serves("api-ms-win-core-file-l1-1-0.dll")); + } +} diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs new file mode 100644 index 0000000..2c5ef87 --- /dev/null +++ b/crates/victory-hle/src/runtime.rs @@ -0,0 +1,18 @@ +//! Process-wide state the implementations need. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0); + +/// Records where the title's main image is mapped. The title expects +/// `GetModuleHandle(NULL)` and friends to return this, not our own exe. +pub fn set_main_image(base: usize) { + MAIN_IMAGE_BASE.store(base, Ordering::Release); +} + +pub fn main_image() -> Option { + match MAIN_IMAGE_BASE.load(Ordering::Acquire) { + 0 => None, + base => Some(base), + } +} diff --git a/crates/victory-hle/tests/no_dll_planting.rs b/crates/victory-hle/tests/no_dll_planting.rs new file mode 100644 index 0000000..4018ee3 --- /dev/null +++ b/crates/victory-hle/tests/no_dll_planting.rs @@ -0,0 +1,29 @@ +//! Host pass-through must only load DLLs from System32, never from the +//! current folder (e.g. a title's folder shipping its own `msvcp140_*.dll`). +#![cfg(windows)] + +use victory_hle::{HleResolver, HostPolicy}; +use victory_pe::ImportSymbol; + +#[test] +fn ignores_dlls_in_current_folder() { + let name = "msvcp140_victorytest.dll"; + assert!( + HostPolicy::default().allows(name), + "test needs an allow-listed name" + ); + assert!(HostPolicy::default().allows("vcruntime140_1.dll")); + + let dir = tempfile::tempdir().unwrap(); + // Any loadable DLL will do. + std::fs::copy(r"C:\Windows\System32\version.dll", dir.path().join(name)).unwrap(); + std::env::set_current_dir(dir.path()).unwrap(); + + let symbol = ImportSymbol::Name { + hint: 0, + name: "GetFileVersionInfoSizeW".into(), + }; + let found = HleResolver::default().classify(name, &symbol); + std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")).unwrap(); + assert_eq!(found, None, "DLL was loaded from the current folder"); +} diff --git a/crates/victory-loader/Cargo.toml b/crates/victory-loader/Cargo.toml new file mode 100644 index 0000000..e5d0a11 --- /dev/null +++ b/crates/victory-loader/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "victory-loader" +description = "Runs an Xbox title's original x86-64 image natively inside our process." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +victory-core.workspace = true +victory-pe.workspace = true +anyhow.workspace = true +thiserror.workspace = true +tracing.workspace = true +blake3.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = [ + "Win32_Foundation", + "Win32_System_Diagnostics_Debug", + "Win32_System_LibraryLoader", + "Win32_System_Memory", + "Win32_System_Threading", +] } + +[dev-dependencies] +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs new file mode 100644 index 0000000..d32a4ab --- /dev/null +++ b/crates/victory-loader/src/lib.rs @@ -0,0 +1,35 @@ +//! Runs a title's original x86-64 code natively, inside our process. +//! +//! Xbox Series X|S executables are x86-64 PE32+ images built for a Zen 2 +//! CPU, so the machine code needs no translation. What differs is the +//! platform underneath, so the loader's job is to: +//! +//! 1. [`prepare`] a lightly patched copy of the image (pure, portable): mark +//! it as a DLL, remove its entry point and import directory, and detach +//! its TLS callbacks, so the Windows loader maps it, relocates it, +//! allocates its static TLS and registers its unwind tables, but runs +//! none of its code and resolves none of its imports; +//! 2. load that copy as a real module (debuggers, profilers, crash dumps +//! and stack walks all see it); this step is Windows-only; +//! 3. bind every import ourselves through an [`ImportResolver`], our +//! runtime (`victory-hle`) or the host, and route anything unresolved +//! to a generated stub that reports exactly what was called; +//! 4. run TLS callbacks and the entry point on a thread with the stack size +//! the image asks for. + +pub mod prepare; +pub mod resolve; +#[cfg(windows)] +mod thunks; +#[cfg(windows)] +mod windows; + +pub use prepare::{PrepareError, PreparedImage, prepare}; +pub use resolve::{ImportResolver, Provenance, Resolution}; +#[cfg(windows)] +pub use thunks::{UnimplementedPolicy, unimplemented_call_count}; +#[cfg(windows)] +pub use windows::{BindReport, LoadedImage, MissingImport, load}; + +/// `DLL_PROCESS_ATTACH`, for TLS callbacks. +pub const DLL_PROCESS_ATTACH: u32 = 1; diff --git a/crates/victory-loader/src/prepare.rs b/crates/victory-loader/src/prepare.rs new file mode 100644 index 0000000..1cbd193 --- /dev/null +++ b/crates/victory-loader/src/prepare.rs @@ -0,0 +1,141 @@ +//! Turns a title's image into something the Windows loader maps but does +//! not run. Pure byte manipulation, so it is testable on any host. + +use victory_pe::layout::{self, dir, dll_flags, file_flags}; +use victory_pe::{ImageInfo, PeError}; + +#[derive(Debug, thiserror::Error)] +pub enum PrepareError { + #[error(transparent)] + Pe(#[from] PeError), + #[error("cannot patch image: {0}")] + Patch(&'static str), +} + +/// A patched copy of an image plus everything we need from the original. +#[derive(Debug, Clone)] +pub struct PreparedImage { + /// Parsed from the *original* bytes: imports, TLS callbacks and entry + /// point as the title expects them. + pub info: ImageInfo, + /// The patched bytes to hand to the Windows loader. + pub bytes: Vec, + /// BLAKE3 of the original bytes: identifies the exact build. + pub original_hash: blake3::Hash, +} + +impl PreparedImage { + /// File name for the patched copy, unique per original build. + pub fn file_name(&self) -> String { + format!("victory-image-{}.dll", &self.original_hash.to_hex()[..16]) + } +} + +/// Produces the patched copy. The changes are: +/// +/// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL +/// and calls nothing; +/// * import and bound-import directories cleared: we bind imports +/// ourselves, using `info.imports` from the original; +/// * TLS callback pointer cleared: the OS still allocates static TLS for +/// the image, but callbacks only run when we call them (after binding); +/// * `FORCE_INTEGRITY` cleared, checksum zeroed: the copy is unsigned. +pub fn prepare(original: &[u8]) -> Result { + let info = ImageInfo::parse(original)?; + let mut bytes = original.to_vec(); + + let fh = layout::file_header_offset(&bytes).ok_or(PrepareError::Patch("no file header"))?; + let opt = + layout::optional_header_offset(&bytes).ok_or(PrepareError::Patch("no optional header"))?; + + let characteristics = info.characteristics | file_flags::DLL; + write_u16( + &mut bytes, + fh + layout::FILE_HEADER_CHARACTERISTICS, + characteristics, + )?; + write_u32(&mut bytes, opt + layout::OPT_ADDRESS_OF_ENTRY_POINT, 0)?; + write_u32(&mut bytes, opt + layout::OPT_CHECKSUM, 0)?; + let dll_characteristics = info.dll_characteristics & !dll_flags::FORCE_INTEGRITY; + write_u16( + &mut bytes, + opt + layout::OPT_DLL_CHARACTERISTICS, + dll_characteristics, + )?; + + for index in [dir::IMPORT, dir::BOUND_IMPORT] { + if let Some(at) = layout::data_directory_offset(&bytes, index) { + write_u32(&mut bytes, at, 0)?; + write_u32(&mut bytes, at + 4, 0)?; + } + } + + if let Some(tls) = &info.tls + && tls.callbacks_va != 0 + { + let at = info + .rva_to_file_offset(tls.directory_rva) + .ok_or(PrepareError::Patch("TLS directory is not file-backed"))?; + write_u64( + &mut bytes, + at as usize + layout::TLS64_ADDRESS_OF_CALLBACKS, + 0, + )?; + } + + Ok(PreparedImage { + info, + bytes, + original_hash: blake3::hash(original), + }) +} + +fn write_u16(bytes: &mut [u8], at: usize, v: u16) -> Result<(), PrepareError> { + write(bytes, at, &v.to_le_bytes()) +} +fn write_u32(bytes: &mut [u8], at: usize, v: u32) -> Result<(), PrepareError> { + write(bytes, at, &v.to_le_bytes()) +} +fn write_u64(bytes: &mut [u8], at: usize, v: u64) -> Result<(), PrepareError> { + write(bytes, at, &v.to_le_bytes()) +} +fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> { + bytes + .get_mut(at..at + v.len()) + .ok_or(PrepareError::Patch("header field outside of file"))? + .copy_from_slice(v); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn patches_own_test_binary() { + let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let prepared = prepare(&original).unwrap(); + assert!(!prepared.info.is_dll(), "info describes the original"); + assert!(prepared.info.import_count() > 0); + + let patched = ImageInfo::parse(&prepared.bytes).unwrap(); + assert!(patched.is_dll()); + assert_eq!(patched.entry_rva, 0); + assert!(patched.imports.is_empty()); + assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0); + if let Some(tls) = &patched.tls { + assert_eq!(tls.callbacks_va, 0); + } + // Nothing else moved: same sections, same size. + assert_eq!(patched.sections.len(), prepared.info.sections.len()); + assert_eq!(prepared.bytes.len(), original.len()); + } + + #[test] + fn file_name_is_stable_per_build() { + let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let a = prepare(&original).unwrap(); + let b = prepare(&original).unwrap(); + assert_eq!(a.file_name(), b.file_name()); + } +} diff --git a/crates/victory-loader/src/resolve.rs b/crates/victory-loader/src/resolve.rs new file mode 100644 index 0000000..c6399d8 --- /dev/null +++ b/crates/victory-loader/src/resolve.rs @@ -0,0 +1,31 @@ +//! How imports get their addresses. + +use victory_pe::ImportSymbol; + +/// Who provides a bound import. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Provenance { + /// Our implementation of the console API. + Hle, + /// The host's own implementation (e.g. Windows API sets that behave the + /// same on console and PC). + Host, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Resolution { + Found { + address: usize, + provenance: Provenance, + }, + /// Nobody implements it; the loader installs a reporting stub. + Missing, +} + +/// Supplies an address for each `dll!symbol` the title imports. +/// +/// `dll` is passed exactly as written in the image; implementations should +/// compare case-insensitively. +pub trait ImportResolver { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution; +} diff --git a/crates/victory-loader/src/thunks.rs b/crates/victory-loader/src/thunks.rs new file mode 100644 index 0000000..9dd2796 --- /dev/null +++ b/crates/victory-loader/src/thunks.rs @@ -0,0 +1,149 @@ +//! Stubs for imports nobody implements yet. +//! +//! Each unresolved import gets 32 bytes of generated code: +//! +//! ```text +//! mov rcx, <&'static ImportSite> ; 48 B9 imm64 +//! mov rax, ; 48 B8 imm64 +//! jmp rax ; FF E0 +//! ``` +//! +//! The jump keeps the title's return address on the stack, so the handler +//! returns straight to the caller. Bring-up then shows exactly which API to +//! implement next, rather than failing at load time. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use anyhow::{Result, bail}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + DebugBreak, FlushInstructionCache, IsDebuggerPresent, +}; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc, VirtualProtect, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// What an unimplemented import does when called. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum UnimplementedPolicy { + /// Log, break into an attached debugger, then abort. The default: + /// silently continuing usually crashes later and further from the cause. + #[default] + Trap, + /// Log once per import and return 0. Useful to push through bring-up. + ReturnZero, +} + +/// Identifies one unresolved import. Leaked: lives as long as the process. +#[derive(Debug)] +pub struct ImportSite { + pub dll: String, + pub symbol: String, + pub policy: UnimplementedPolicy, + pub calls: AtomicU64, +} + +static UNIMPLEMENTED_CALLS: AtomicU64 = AtomicU64::new(0); + +/// Total number of calls that reached an unimplemented-import stub. +pub fn unimplemented_call_count() -> u64 { + UNIMPLEMENTED_CALLS.load(Ordering::Relaxed) +} + +extern "system" fn unimplemented_import(site: &'static ImportSite) -> u64 { + UNIMPLEMENTED_CALLS.fetch_add(1, Ordering::Relaxed); + let previous = site.calls.fetch_add(1, Ordering::Relaxed); + match site.policy { + UnimplementedPolicy::ReturnZero => { + if previous == 0 { + tracing::warn!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called, returning 0"); + } + 0 + } + UnimplementedPolicy::Trap => { + tracing::error!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called"); + eprintln!( + "VIctory: unimplemented import {}!{} called", + site.dll, site.symbol + ); + // SAFETY: plain Win32 calls without preconditions. + unsafe { + if IsDebuggerPresent() != 0 { + DebugBreak(); + } + } + std::process::abort(); + } + } +} + +const THUNK_SIZE: usize = 32; + +/// Executable memory holding one stub per unresolved import. +pub(crate) struct ThunkBlock { + base: *mut u8, + len: usize, + used: usize, +} + +impl ThunkBlock { + /// Reserves room for `count` stubs (writable until [`Self::seal`]). + pub(crate) fn new(count: usize) -> Result { + let len = (count.max(1) * THUNK_SIZE).next_multiple_of(4096); + // SAFETY: fresh anonymous allocation; no existing memory is touched. + let base = unsafe { + VirtualAlloc( + std::ptr::null(), + len, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + } as *mut u8; + if base.is_null() { + bail!( + "VirtualAlloc for import stubs failed: {}", + std::io::Error::last_os_error() + ); + } + Ok(ThunkBlock { base, len, used: 0 }) + } + + /// Emits a stub for `site` and returns its address. + pub(crate) fn emit(&mut self, site: &'static ImportSite) -> Result { + if self.used + THUNK_SIZE > self.len { + bail!("import stub block is full"); + } + let mut code = [0xCC_u8; THUNK_SIZE]; // int3 padding + code[0..2].copy_from_slice(&[0x48, 0xB9]); + code[2..10].copy_from_slice(&(site as *const ImportSite as u64).to_le_bytes()); + code[10..12].copy_from_slice(&[0x48, 0xB8]); + let handler = unimplemented_import as extern "system" fn(&'static ImportSite) -> u64; + code[12..20].copy_from_slice(&(handler as *const () as u64).to_le_bytes()); + code[20..22].copy_from_slice(&[0xFF, 0xE0]); + // SAFETY: `used + THUNK_SIZE <= len`, and the block is still writable. + let at = unsafe { + let at = self.base.add(self.used); + std::ptr::copy_nonoverlapping(code.as_ptr(), at, THUNK_SIZE); + at + }; + self.used += THUNK_SIZE; + Ok(at as usize) + } + + /// Makes the block read+execute. The block is intentionally leaked: + /// title code may hold these addresses for the life of the process. + pub(crate) fn seal(self) -> Result<()> { + let mut old = 0; + // SAFETY: `base..base+len` is the allocation made in `new`. + let ok = unsafe { VirtualProtect(self.base as _, self.len, PAGE_EXECUTE_READ, &mut old) }; + if ok == 0 { + bail!( + "VirtualProtect for import stubs failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: flushing our own process's instruction cache for our own block. + unsafe { FlushInstructionCache(GetCurrentProcess(), self.base as _, self.len) }; + Ok(()) + } +} diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs new file mode 100644 index 0000000..389a03b --- /dev/null +++ b/crates/victory-loader/src/windows.rs @@ -0,0 +1,250 @@ +//! Loading a prepared image as a real Windows module and binding it. + +use std::ffi::{CString, c_void}; +use std::os::windows::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::AtomicU64; + +use anyhow::{Context, Result, bail}; +use victory_pe::{ImageInfo, ImportSymbol}; +use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW}; +use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + +use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy}; +use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution}; + +/// A title image mapped into this process. +#[derive(Debug)] +pub struct LoadedImage { + module: HMODULE, + path: PathBuf, + info: ImageInfo, +} + +// SAFETY: HMODULE is a process-wide handle (the base address); using it from +// any thread is fine. +unsafe impl Send for LoadedImage {} +// SAFETY: as above; `LoadedImage` has no interior mutability. +unsafe impl Sync for LoadedImage {} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MissingImport { + pub dll: String, + pub symbol: String, +} + +/// Outcome of [`LoadedImage::bind_imports`]. +#[derive(Debug, Default, Clone)] +pub struct BindReport { + pub hle: usize, + pub host: usize, + pub missing: Vec, +} + +/// Writes the prepared copy into `dir` and maps it with the Windows loader. +/// +/// `dir` receives derived game data, so it must be outside the repository. +pub fn load(prepared: &PreparedImage, dir: &Path) -> Result { + victory_core::ensure_outside_repo(dir)?; + std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; + let path = dir.join(prepared.file_name()); + write_if_changed(&path, &prepared.bytes)?; + + let wide: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + // SAFETY: `wide` is a NUL-terminated path. The image has no entry point + // and no imports, so loading it runs no title code. + let module = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0) }; + if module.is_null() { + bail!( + "LoadLibraryExW({}) failed: {}{}", + path.display(), + std::io::Error::last_os_error(), + if prepared.info.has_relocations { + "" + } else { + " (image has no relocations; its preferred base may be taken)" + } + ); + } + let loaded = LoadedImage { + module, + path, + info: prepared.info.clone(), + }; + tracing::info!( + base = format_args!("{:#x}", loaded.base()), + preferred = format_args!("{:#x}", loaded.info.image_base), + path = %loaded.path.display(), + "image mapped" + ); + Ok(loaded) +} + +fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> { + if std::fs::read(path).is_ok_and(|existing| existing == bytes) { + return Ok(()); + } + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?; + std::fs::rename(&tmp, path).with_context(|| format!("renaming to {}", path.display()))?; + Ok(()) +} + +impl LoadedImage { + pub fn base(&self) -> usize { + self.module as usize + } + + /// Parsed from the original image (imports, entry point, TLS callbacks). + pub fn info(&self) -> &ImageInfo { + &self.info + } + + /// Address of an export of the image, if it has one by that name. + pub fn export(&self, name: &str) -> Option { + let name = CString::new(name).ok()?; + // SAFETY: valid module handle and NUL-terminated name. + unsafe { GetProcAddress(self.module, name.as_ptr().cast()) } + .map(|f| f as *const () as usize) + } + + /// Fills every IAT slot of the image. + /// + /// Each import goes to `resolver`; whatever it cannot resolve gets an + /// unimplemented-import stub that behaves according to `policy`. + pub fn bind_imports( + &self, + resolver: &dyn ImportResolver, + policy: UnimplementedPolicy, + ) -> Result { + let mut report = BindReport::default(); + let mut slots: Vec<(u32, usize)> = Vec::with_capacity(self.info.import_count()); + let mut unresolved: Vec<(u32, &str, &ImportSymbol)> = Vec::new(); + + // Delay-load slots are bound eagerly too, so the title's own + // delay-load helper (which would ask the host) never runs. + for module in self.info.imports.iter().chain(&self.info.delay_imports) { + for entry in &module.entries { + match resolver.resolve(&module.dll, &entry.symbol) { + Resolution::Found { + address, + provenance, + } => { + match provenance { + Provenance::Hle => report.hle += 1, + Provenance::Host => report.host += 1, + } + slots.push((entry.iat_slot_rva, address)); + } + Resolution::Missing => { + unresolved.push((entry.iat_slot_rva, &module.dll, &entry.symbol)); + } + } + } + } + + if !unresolved.is_empty() { + let mut block = ThunkBlock::new(unresolved.len())?; + for (slot, dll, symbol) in unresolved { + let site: &'static ImportSite = Box::leak(Box::new(ImportSite { + dll: dll.to_owned(), + symbol: symbol.to_string(), + policy, + calls: AtomicU64::new(0), + })); + slots.push((slot, block.emit(site)?)); + report.missing.push(MissingImport { + dll: site.dll.clone(), + symbol: site.symbol.clone(), + }); + } + block.seal()?; + } + + self.write_slots(&slots)?; + tracing::info!( + hle = report.hle, + host = report.host, + missing = report.missing.len(), + "imports bound" + ); + Ok(report) + } + + /// Protects and restores each slot on its own: import tables can sit in + /// sections with different protections (delay-load tables in `.didat`). + fn write_slots(&self, slots: &[(u32, usize)]) -> Result<()> { + for &(rva, address) in slots { + let slot = (self.base() + rva as usize) as *mut u64; + let mut old = 0; + // SAFETY: the parser only yields slots inside the image. + if unsafe { VirtualProtect(slot as *const c_void, 8, PAGE_READWRITE, &mut old) } == 0 { + bail!( + "VirtualProtect(IAT slot {rva:#x}) failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: inside the image, now writable, 8-byte aligned by the PE format. + unsafe { slot.write_volatile(address as u64) }; + let mut ignored = 0; + // SAFETY: restoring the protection we just changed. + unsafe { VirtualProtect(slot as *const c_void, 8, old, &mut ignored) }; + } + Ok(()) + } + + /// Calls the image's TLS callbacks with `reason` (e.g. `DLL_PROCESS_ATTACH`). + /// + /// # Safety + /// Runs title code. Imports must be bound first. + pub unsafe fn run_tls_callbacks(&self, reason: u32) { + let Some(tls) = &self.info.tls else { return }; + for &rva in &tls.callback_rvas { + type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void); + // SAFETY: the RVA came from the image's own TLS directory. + let callback: TlsCallback = unsafe { std::mem::transmute(self.base() + rva as usize) }; + // SAFETY: the caller guarantees imports are bound. + unsafe { callback(self.module, reason, std::ptr::null_mut()) }; + } + } + + /// Starts the title: on a new thread with the stack size from the image + /// header, runs the TLS callbacks (`DLL_PROCESS_ATTACH`), then the + /// original entry point. Returns the thread so the caller can join it. + /// + /// # Safety + /// Runs title code. Imports must be bound first. + pub unsafe fn spawn_main(self: std::sync::Arc) -> Result> { + if self.info.entry_rva == 0 { + bail!("image has no entry point"); + } + let stack = usize::try_from(self.info.stack_reserve) + .unwrap_or(usize::MAX) + .max(1 << 20); + std::thread::Builder::new() + .name("title-main".into()) + .stack_size(stack) + .spawn(move || { + // SAFETY: forwarded from the caller of `spawn_main`. + unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) }; + type Entry = unsafe extern "system" fn(*mut c_void) -> u32; + // SAFETY: the entry RVA came from the original image header. + let entry: Entry = + unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; + // SAFETY: forwarded from the caller of `spawn_main`. + unsafe { entry(std::ptr::null_mut()) } + }) + .context("spawning title main thread") + } + + /// Unmaps the image. + /// + /// # Safety + /// No title code may be running or run later, and no pointer into the + /// image may be used afterwards. + pub unsafe fn unload(self) { + // SAFETY: guaranteed by the caller. + unsafe { FreeLibrary(self.module) }; + } +} diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs new file mode 100644 index 0000000..859ecdd --- /dev/null +++ b/crates/victory-loader/tests/load_probe.rs @@ -0,0 +1,155 @@ +//! End-to-end: prepare, load, bind and call into a stand-in title +//! (tests/fixtures/hle-probe), without any game data. +#![cfg(windows)] + +use std::ffi::CString; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use victory_loader::{ + ImportResolver, Provenance, Resolution, UnimplementedPolicy, prepare, unimplemented_call_count, +}; +use victory_pe::ImportSymbol; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") +} + +/// Builds the fixture into its own target dir (the outer cargo holds the +/// lock on the main one while tests run). +fn build_probe() -> PathBuf { + let root = workspace_root(); + let manifest = root.join("tests/fixtures/hle-probe/Cargo.toml"); + let target = root.join("target/fixtures"); + let status = Command::new(env!("CARGO")) + .args(["build", "--quiet", "--manifest-path"]) + .arg(&manifest) + .arg("--target-dir") + .arg(&target) + .status() + .expect("running cargo"); + assert!(status.success(), "building hle-probe failed"); + target.join("debug").join("hle_probe.dll") +} + +extern "system" fn fake_xgameruntime_initialize() -> i32 { + 0x1234 +} +extern "system" fn fake_get_tick_count() -> u32 { + 777 +} +extern "system" fn fake_delayed() -> u32 { + 4242 +} + +struct TestResolver; + +impl ImportResolver for TestResolver { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + let dll = dll.to_ascii_lowercase(); + let ImportSymbol::Name { name, .. } = symbol else { + return Resolution::Missing; + }; + let hle = match (dll.as_str(), name.as_str()) { + ("xgameruntime.dll", "XGameRuntimeInitialize") => { + Some(fake_xgameruntime_initialize as *const () as usize) + } + ("kernel32.dll", "GetTickCount") => Some(fake_get_tick_count as *const () as usize), + ("victory-probe-delayed.dll", "VIctoryProbeDelayed") => { + Some(fake_delayed as *const () as usize) + } + _ => None, + }; + if let Some(address) = hle { + return Resolution::Found { + address, + provenance: Provenance::Hle, + }; + } + host(&dll, name) + .map(|address| Resolution::Found { + address, + provenance: Provenance::Host, + }) + .unwrap_or(Resolution::Missing) + } +} + +fn host(dll: &str, name: &str) -> Option { + let dll = CString::new(dll).ok()?; + let name = CString::new(name).ok()?; + // SAFETY: NUL-terminated strings; loading system DLLs into the test process. + unsafe { + let module = LoadLibraryA(dll.as_ptr().cast()); + if module.is_null() { + return None; + } + GetProcAddress(module, name.as_ptr().cast()).map(|f| f as *const () as usize) + } +} + +#[test] +fn loads_binds_and_calls_probe() { + let dll = build_probe(); + let original = std::fs::read(&dll).unwrap(); + let prepared = prepare(&original).unwrap(); + + let imports: Vec<_> = prepared + .info + .imports + .iter() + .map(|m| m.dll.to_ascii_lowercase()) + .collect(); + assert!( + imports.contains(&"xgameruntime.dll".to_owned()), + "{imports:?}" + ); + assert!( + imports.contains(&"victory-probe-missing.dll".to_owned()), + "{imports:?}" + ); + assert!( + prepared + .info + .delay_imports + .iter() + .any(|m| m.dll.eq_ignore_ascii_case("victory-probe-delayed.dll")), + "fixture must delay-load victory-probe-delayed.dll" + ); + + let dir = tempfile::tempdir().unwrap(); + let image = victory_loader::load(&prepared, dir.path()).unwrap(); + let report = image + .bind_imports(&TestResolver, UnimplementedPolicy::ReturnZero) + .unwrap(); + + assert_eq!(report.hle, 3); + assert!(report.host > 0); + assert_eq!(report.missing.len(), 1); + assert_eq!(report.missing[0].symbol, "VIctoryProbeNotImplemented"); + + let call = |name: &str| -> usize { image.export(name).unwrap_or_else(|| panic!("{name}")) }; + // SAFETY: the exports have the signatures declared in the fixture and + // every import they use has been bound. + unsafe { + let f: extern "system" fn() -> i32 = std::mem::transmute(call("probe_xgameruntime_init")); + assert_eq!(f(), 0x1234, "console API must reach our implementation"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_tick")); + assert_eq!(f(), 777, "host API must be overridable"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_pid")); + assert_eq!(f(), std::process::id(), "host API must pass through"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_delayed")); + assert_eq!(f(), 4242, "delay-loaded API must be bound"); + + let before = unimplemented_call_count(); + let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_missing")); + assert_eq!(f(), 0); + assert_eq!(unimplemented_call_count(), before + 1); + + image.unload(); + } +} diff --git a/crates/victory-pe/Cargo.toml b/crates/victory-pe/Cargo.toml new file mode 100644 index 0000000..0f7c457 --- /dev/null +++ b/crates/victory-pe/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "victory-pe" +description = "Read-only analysis of PE32+ images and COFF import libraries." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +object.workspace = true +thiserror.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-pe/src/image.rs b/crates/victory-pe/src/image.rs new file mode 100644 index 0000000..4acc6e3 --- /dev/null +++ b/crates/victory-pe/src/image.rs @@ -0,0 +1,472 @@ +use object::LittleEndian as LE; +use object::Object; +use object::pe::{self, ImageNtHeaders64}; +use object::read::pe::{ + ExportTarget, ImageNtHeaders, ImageOptionalHeader, Import, ImportTable, ImportThunkList, + PeFile64, +}; + +use crate::layout::{self, dir}; +use crate::{MACHINE_AMD64, PeError}; + +/// Everything we need to know about a PE32+ image, extracted in one pass. +#[derive(Debug, Clone)] +pub struct ImageInfo { + pub machine: u16, + /// `IMAGE_FILE_HEADER::Characteristics`. + pub characteristics: u16, + pub timestamp: u32, + pub subsystem: u16, + /// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics`. + pub dll_characteristics: u16, + pub image_base: u64, + pub size_of_image: u32, + pub entry_rva: u32, + pub stack_reserve: u64, + pub stack_commit: u64, + pub sections: Vec, + pub imports: Vec, + pub delay_imports: Vec, + pub exports: Vec, + pub tls: Option, + pub has_relocations: bool, + pub has_exception_table: bool, + pub has_load_config: bool, + pub codeview: Option, +} + +#[derive(Debug, Clone)] +pub struct SectionInfo { + pub name: String, + pub rva: u32, + pub virtual_size: u32, + pub file_offset: u32, + pub file_size: u32, + pub characteristics: u32, +} + +/// One imported DLL and the functions taken from it. +#[derive(Debug, Clone)] +pub struct ImportModule { + /// DLL name exactly as written in the image (case preserved). + pub dll: String, + pub entries: Vec, +} + +#[derive(Debug, Clone)] +pub struct ImportEntry { + pub symbol: ImportSymbol, + /// RVA of the 8-byte IAT slot the loader must fill in. + pub iat_slot_rva: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ImportSymbol { + Name { hint: u16, name: String }, + Ordinal(u16), +} + +impl std::fmt::Display for ImportSymbol { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ImportSymbol::Name { name, .. } => f.write_str(name), + ImportSymbol::Ordinal(o) => write!(f, "#{o}"), + } + } +} + +#[derive(Debug, Clone)] +pub struct ExportInfo { + pub name: Option, + pub ordinal: u16, + /// `None` for forwarded exports. + pub rva: Option, + /// `"dll.name"` or `"dll.#ordinal"` for forwarded exports. + pub forward: Option, +} + +#[derive(Debug, Clone)] +pub struct TlsInfo { + /// RVA of `IMAGE_TLS_DIRECTORY64`. + pub directory_rva: u32, + /// VA (at the preferred base) of the callback array, 0 if none. + pub callbacks_va: u64, + /// Callback RVAs, in call order. + pub callback_rvas: Vec, +} + +/// CodeView (RSDS) record: identifies the exact build that produced an image. +#[derive(Debug, Clone)] +pub struct CodeViewInfo { + pub pdb_path: String, + pub guid: [u8; 16], + pub age: u32, +} + +impl CodeViewInfo { + /// The key symbol servers use: GUID (Windows byte order) + age. + pub fn symbol_key(&self) -> String { + let g = &self.guid; + let d1 = u32::from_le_bytes([g[0], g[1], g[2], g[3]]); + let d2 = u16::from_le_bytes([g[4], g[5]]); + let d3 = u16::from_le_bytes([g[6], g[7]]); + let mut s = format!("{d1:08X}{d2:04X}{d3:04X}"); + for b in &g[8..] { + s.push_str(&format!("{b:02X}")); + } + s.push_str(&format!("{:X}", self.age)); + s + } +} + +/// Upper bound on TLS callbacks we are willing to walk (defends against garbage). +const MAX_TLS_CALLBACKS: usize = 1024; + +impl ImageInfo { + /// Parses a complete PE32+ x86-64 image from its file bytes. + pub fn parse(data: &[u8]) -> Result { + let kind = object::FileKind::parse(data)?; + if kind != object::FileKind::Pe64 { + return Err(PeError::Unsupported(format!( + "expected PE32+, found {kind:?}" + ))); + } + let file = PeFile64::parse(data)?; + let nt = file.nt_headers(); + let fh = nt.file_header(); + let opt = nt.optional_header(); + + let machine = fh.machine.get(LE).0; + if machine != MACHINE_AMD64 { + return Err(PeError::Unsupported(format!( + "machine 0x{machine:04x} is not AMD64" + ))); + } + + let sections = file + .section_table() + .iter() + .map(|s| SectionInfo { + name: String::from_utf8_lossy(s.raw_name()).into_owned(), + rva: s.virtual_address.get(LE), + virtual_size: s.virtual_size.get(LE), + file_offset: s.pointer_to_raw_data.get(LE), + file_size: s.size_of_raw_data.get(LE), + characteristics: s.characteristics.get(LE).0, + }) + .collect(); + + let dir_present = |index: usize| { + file.data_directory(index) + .is_some_and(|d| d.virtual_address.get(LE) != 0 && d.size.get(LE) != 0) + }; + + let imports = match file.import_table()? { + Some(table) => parse_imports(&table, opt.size_of_image())?, + None => Vec::new(), + }; + let delay_imports = parse_delay_imports(&file, opt.size_of_image())?; + let exports = parse_exports(&file)?; + let tls = parse_tls(&file, data, opt.image_base())?; + let codeview = file.pdb_info()?.map(|cv| CodeViewInfo { + pdb_path: String::from_utf8_lossy(cv.path()).into_owned(), + guid: cv.guid(), + age: cv.age(), + }); + + Ok(ImageInfo { + machine, + characteristics: fh.characteristics.get(LE).0, + timestamp: fh.time_date_stamp.get(LE), + subsystem: opt.subsystem().0, + dll_characteristics: opt.dll_characteristics().0, + image_base: opt.image_base(), + size_of_image: opt.size_of_image(), + entry_rva: opt.address_of_entry_point(), + stack_reserve: opt.size_of_stack_reserve(), + stack_commit: opt.size_of_stack_commit(), + sections, + imports, + delay_imports, + exports, + tls, + has_relocations: dir_present(dir::BASERELOC) + && !has_flag( + fh.characteristics.get(LE).0, + layout::file_flags::RELOCS_STRIPPED, + ), + has_exception_table: dir_present(dir::EXCEPTION), + has_load_config: dir_present(dir::LOAD_CONFIG), + codeview, + }) + } + + pub fn is_dll(&self) -> bool { + has_flag(self.characteristics, layout::file_flags::DLL) + } + + /// Maps an RVA to an offset in the file, if it is backed by file data. + pub fn rva_to_file_offset(&self, rva: u32) -> Option { + self.sections.iter().find_map(|s| { + let delta = rva.checked_sub(s.rva)?; + // Raw data may be padded past the virtual size; that padding is + // not part of the section in memory. + let backed = match s.virtual_size { + 0 => s.file_size, + vs => vs.min(s.file_size), + }; + (delta < backed).then(|| s.file_offset + delta) + }) + } + + pub fn import_count(&self) -> usize { + self.imports.iter().map(|m| m.entries.len()).sum() + } + + pub fn subsystem_name(&self) -> &'static str { + use layout::subsystem::*; + match self.subsystem { + WINDOWS_GUI => "windows-gui", + WINDOWS_CUI => "windows-cui", + XBOX => "xbox", + XBOX_CODE_CATALOG => "xbox-code-catalog", + _ => "other", + } + } +} + +fn has_flag(value: u16, flag: u16) -> bool { + value & flag != 0 +} + +fn utf8(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes).into_owned() +} + +fn convert_import(import: Import<'_>) -> ImportSymbol { + match import { + Import::Ordinal(o) => ImportSymbol::Ordinal(o), + Import::Name(hint, name) => ImportSymbol::Name { + hint, + name: utf8(name), + }, + } +} + +fn parse_imports( + table: &ImportTable<'_>, + size_of_image: u32, +) -> Result, PeError> { + let mut modules = Vec::new(); + let mut descriptors = table.descriptors()?; + while let Some(desc) = descriptors.next()? { + let iat_rva = desc.first_thunk.get(LE); + // Prefer the unbound name table; fall back to the IAT for old linkers. + let int_rva = match desc.original_first_thunk.get(LE) { + 0 => iat_rva, + rva => rva, + }; + modules.push(ImportModule { + dll: utf8(table.name(desc.name.get(LE))?), + entries: entries(table.thunks(int_rva)?, iat_rva, size_of_image, |t| { + table.import::(t) + })?, + }); + } + Ok(modules) +} + +fn parse_delay_imports( + file: &PeFile64<'_>, + size_of_image: u32, +) -> Result, PeError> { + let Some(table) = file.delay_load_import_table()? else { + return Ok(Vec::new()); + }; + let mut modules = Vec::new(); + let mut descriptors = table.descriptors()?; + while let Some(desc) = descriptors.next()? { + modules.push(ImportModule { + dll: utf8(table.name(desc.dll_name_rva.get(LE))?), + entries: entries( + table.thunks(desc.import_name_table_rva.get(LE))?, + desc.import_address_table_rva.get(LE), + size_of_image, + |t| table.import::(t), + )?, + }); + } + Ok(modules) +} + +/// Pairs each name-table entry with its IAT slot. The IAT RVA is not checked +/// by `object`, so every slot is checked to lie inside the image here. +fn entries<'data>( + mut thunks: ImportThunkList<'data>, + iat_rva: u32, + size_of_image: u32, + import: impl Fn(pe::ImageThunkData64) -> object::read::Result>, +) -> Result, PeError> { + let mut entries = Vec::new(); + while let Some(thunk) = thunks.next::()? { + let iat_slot_rva = u32::try_from(entries.len() * 8) + .ok() + .and_then(|offset| iat_rva.checked_add(offset)) + .filter(|&rva| rva.checked_add(8).is_some_and(|end| end <= size_of_image)) + .ok_or_else(|| { + PeError::Malformed(format!("IAT at {iat_rva:#x} runs outside the image")) + })?; + entries.push(ImportEntry { + symbol: convert_import(import(thunk)?), + iat_slot_rva, + }); + } + Ok(entries) +} + +fn parse_exports(file: &PeFile64<'_>) -> Result, PeError> { + let Some(table) = file.export_table()? else { + return Ok(Vec::new()); + }; + Ok(table + .exports()? + .into_iter() + .map(|e| { + let (rva, forward) = match e.target { + ExportTarget::Address(rva) => (Some(rva), None), + ExportTarget::ForwardByName(d, n) => { + (None, Some(format!("{}.{}", utf8(d), utf8(n)))) + } + ExportTarget::ForwardByOrdinal(d, o) => { + (None, Some(format!("{}.#{}", utf8(d), o.0))) + } + }; + ExportInfo { + name: e.name.map(utf8), + ordinal: e.ordinal.0, + rva, + forward, + } + }) + .collect()) +} + +fn parse_tls( + file: &PeFile64<'_>, + data: &[u8], + image_base: u64, +) -> Result, PeError> { + let Some(dd) = file.data_directory(pe::IMAGE_DIRECTORY_ENTRY_TLS) else { + return Ok(None); + }; + let directory_rva = dd.virtual_address.get(LE); + if directory_rva == 0 { + return Ok(None); + } + let sections = file.section_table(); + let tls = sections + .pe_data_at(data, directory_rva) + .ok_or_else(|| PeError::Malformed("TLS directory outside of sections".into()))?; + let callbacks_va = layout::read_u64(tls, layout::TLS64_ADDRESS_OF_CALLBACKS) + .ok_or_else(|| PeError::Malformed("truncated TLS directory".into()))?; + + let mut callback_rvas = Vec::new(); + if callbacks_va != 0 { + let array_rva = va_to_rva(callbacks_va, image_base)?; + let array = sections + .pe_data_at(data, array_rva) + .ok_or_else(|| PeError::Malformed("TLS callback array outside of sections".into()))?; + for slot in array.as_chunks::<8>().0.iter().take(MAX_TLS_CALLBACKS) { + let va = u64::from_le_bytes(*slot); + if va == 0 { + break; + } + callback_rvas.push(va_to_rva(va, image_base)?); + } + } + Ok(Some(TlsInfo { + directory_rva, + callbacks_va, + callback_rvas, + })) +} + +fn va_to_rva(va: u64, image_base: u64) -> Result { + va.checked_sub(image_base) + .and_then(|rva| u32::try_from(rva).ok()) + .ok_or_else(|| PeError::Malformed(format!("VA 0x{va:x} is outside the image"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The test binary itself is a real MSVC-linked PE32+ image. + fn own_image() -> Vec { + std::fs::read(std::env::current_exe().unwrap()).unwrap() + } + + #[test] + fn parses_own_test_binary() { + let info = ImageInfo::parse(&own_image()).unwrap(); + assert_eq!(info.machine, MACHINE_AMD64); + assert!(!info.is_dll()); + assert!(info.entry_rva != 0); + assert!(info.has_exception_table, "x64 images always carry .pdata"); + assert!(info.sections.iter().any(|s| s.name.starts_with(".text"))); + let kernel32 = info + .imports + .iter() + .find(|m| m.dll.eq_ignore_ascii_case("kernel32.dll")) + .expect("Rust std imports kernel32"); + assert!(kernel32.entries.iter().all(|e| e.iat_slot_rva != 0)); + // Rust std uses static TLS, so a TLS directory must be present (its + // callback array may legitimately be empty). + assert!(info.tls.is_some()); + } + + #[test] + fn rva_to_file_offset_maps_entry_point() { + let data = own_image(); + let info = ImageInfo::parse(&data).unwrap(); + let off = info.rva_to_file_offset(info.entry_rva).unwrap() as usize; + assert!(off < data.len()); + } + + #[test] + fn rejects_garbage_without_panicking() { + assert!(ImageInfo::parse(b"").is_err()); + assert!(ImageInfo::parse(b"MZ not really").is_err()); + let mut truncated = own_image(); + truncated.truncate(0x200); + assert!(ImageInfo::parse(&truncated).is_err()); + } + + #[test] + fn rejects_iat_outside_image() { + let mut data = own_image(); + let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap(); + let import_rva = layout::read_u32(&data, dd).unwrap(); + let desc = ImageInfo::parse(&data) + .unwrap() + .rva_to_file_offset(import_rva) + .unwrap() as usize; + // First descriptor's FirstThunk, at the 4 GiB limit: used to overflow. + data[desc + 16..desc + 20].copy_from_slice(&0xFFFF_FFF8u32.to_le_bytes()); + assert!(matches!( + ImageInfo::parse(&data), + Err(PeError::Malformed(_)) + )); + } +} + +#[cfg(test)] +mod dbg_tls { + #[test] + fn dump_tls() { + let data = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let info = super::ImageInfo::parse(&data).unwrap(); + eprintln!("TLS = {:?}", info.tls); + eprintln!("image_base = {:x}", info.image_base); + } +} diff --git a/crates/victory-pe/src/implib.rs b/crates/victory-pe/src/implib.rs new file mode 100644 index 0000000..234c1ec --- /dev/null +++ b/crates/victory-pe/src/implib.rs @@ -0,0 +1,66 @@ +//! COFF import libraries (`.lib`). +//! +//! An umbrella import library tells us which DLL provides each API that a +//! console title may link against. That is the map the runtime needs to +//! decide which of our implementations answers which import. + +use object::read::archive::ArchiveFile; +use object::read::coff::{ImportFile, ImportName, ImportType}; + +use crate::{ImportSymbol, PeError}; + +/// One `dll!export` pair described by an import library. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct LibImport { + pub dll: String, + pub export: ImportSymbol, + pub kind: LibImportKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum LibImportKind { + Code, + Data, + Const, +} + +/// Result of reading an import library. +#[derive(Debug, Default)] +pub struct ImportLibrary { + pub imports: Vec, + /// Members that are not short-format import objects (regular objects, + /// long-format import descriptors). Reported so nothing is silently lost. + pub other_members: usize, +} + +impl ImportLibrary { + pub fn parse(data: &[u8]) -> Result { + let archive = ArchiveFile::parse(data)?; + let mut lib = ImportLibrary::default(); + for member in archive.members() { + let member = member?; + let bytes = member.data(data)?; + match ImportFile::parse(bytes) { + Ok(import) => lib.imports.push(LibImport { + dll: String::from_utf8_lossy(import.dll()).into_owned(), + export: match import.import() { + ImportName::Name(name) => ImportSymbol::Name { + hint: 0, + name: String::from_utf8_lossy(name).into_owned(), + }, + ImportName::Ordinal(o) => ImportSymbol::Ordinal(o), + }, + kind: match import.import_type() { + ImportType::Code => LibImportKind::Code, + ImportType::Data => LibImportKind::Data, + ImportType::Const => LibImportKind::Const, + }, + }), + Err(_) => lib.other_members += 1, + } + } + lib.imports.sort(); + lib.imports.dedup(); + Ok(lib) + } +} diff --git a/crates/victory-pe/src/layout.rs b/crates/victory-pe/src/layout.rs new file mode 100644 index 0000000..fd99b7f --- /dev/null +++ b/crates/victory-pe/src/layout.rs @@ -0,0 +1,91 @@ +//! Raw byte offsets of PE32+ header fields, for code that patches images. +//! +//! All offsets are relative to the start of the structure named in the +//! constant's prefix. They follow the published PE/COFF specification. + +/// Offset of `e_lfanew` (u32) in the DOS header. +pub const DOS_E_LFANEW: usize = 0x3C; + +/// Size of the `PE\0\0` signature that precedes the file header. +pub const NT_SIGNATURE_SIZE: usize = 4; +/// Size of `IMAGE_FILE_HEADER`. +pub const FILE_HEADER_SIZE: usize = 20; + +/// `IMAGE_FILE_HEADER::Characteristics` (u16). +pub const FILE_HEADER_CHARACTERISTICS: usize = 18; + +/// `IMAGE_OPTIONAL_HEADER64::AddressOfEntryPoint` (u32). +pub const OPT_ADDRESS_OF_ENTRY_POINT: usize = 16; +/// `IMAGE_OPTIONAL_HEADER64::CheckSum` (u32). +pub const OPT_CHECKSUM: usize = 64; +/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` (u16). +pub const OPT_DLL_CHARACTERISTICS: usize = 70; +/// `IMAGE_OPTIONAL_HEADER64::NumberOfRvaAndSizes` (u32). +pub const OPT_NUMBER_OF_RVA_AND_SIZES: usize = 108; +/// First `IMAGE_DATA_DIRECTORY` entry (each is `{ rva: u32, size: u32 }`). +pub const OPT_DATA_DIRECTORY: usize = 112; +/// Size of one `IMAGE_DATA_DIRECTORY`. +pub const DATA_DIRECTORY_SIZE: usize = 8; + +/// `IMAGE_TLS_DIRECTORY64::AddressOfCallBacks` (u64 VA). +pub const TLS64_ADDRESS_OF_CALLBACKS: usize = 24; + +/// Data directory indices. +pub mod dir { + pub const IMPORT: usize = 1; + pub const EXCEPTION: usize = 3; + pub const BASERELOC: usize = 5; + pub const LOAD_CONFIG: usize = 10; + pub const BOUND_IMPORT: usize = 11; +} + +/// `IMAGE_FILE_HEADER::Characteristics` flags. +pub mod file_flags { + pub const RELOCS_STRIPPED: u16 = 0x0001; + pub const DLL: u16 = 0x2000; +} + +/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` flags. +pub mod dll_flags { + pub const HIGH_ENTROPY_VA: u16 = 0x0020; + pub const DYNAMIC_BASE: u16 = 0x0040; + pub const FORCE_INTEGRITY: u16 = 0x0080; + pub const NX_COMPAT: u16 = 0x0100; + pub const APPCONTAINER: u16 = 0x1000; + pub const GUARD_CF: u16 = 0x4000; +} + +/// `IMAGE_OPTIONAL_HEADER64::Subsystem` values. +pub mod subsystem { + pub const WINDOWS_GUI: u16 = 2; + pub const WINDOWS_CUI: u16 = 3; + pub const XBOX: u16 = 14; + pub const XBOX_CODE_CATALOG: u16 = 17; +} + +/// Offset of the optional header from the start of the file. +pub fn optional_header_offset(data: &[u8]) -> Option { + let lfanew = read_u32(data, DOS_E_LFANEW)? as usize; + Some(lfanew + NT_SIGNATURE_SIZE + FILE_HEADER_SIZE) +} + +/// Offset of the file header from the start of the file. +pub fn file_header_offset(data: &[u8]) -> Option { + let lfanew = read_u32(data, DOS_E_LFANEW)? as usize; + Some(lfanew + NT_SIGNATURE_SIZE) +} + +/// Offset of data directory `index` from the start of the file. +pub fn data_directory_offset(data: &[u8], index: usize) -> Option { + let opt = optional_header_offset(data)?; + let count = read_u32(data, opt + OPT_NUMBER_OF_RVA_AND_SIZES)? as usize; + (index < count).then_some(opt + OPT_DATA_DIRECTORY + index * DATA_DIRECTORY_SIZE) +} + +pub fn read_u32(data: &[u8], at: usize) -> Option { + Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?)) +} + +pub fn read_u64(data: &[u8], at: usize) -> Option { + Some(u64::from_le_bytes(data.get(at..at + 8)?.try_into().ok()?)) +} diff --git a/crates/victory-pe/src/lib.rs b/crates/victory-pe/src/lib.rs new file mode 100644 index 0000000..89cd915 --- /dev/null +++ b/crates/victory-pe/src/lib.rs @@ -0,0 +1,35 @@ +//! Read-only analysis of PE32+ (x86-64) images and COFF import libraries. +//! +//! Xbox Series X|S titles are ordinary x86-64 PE32+ images (the console CPU +//! is a Zen 2), so the same parser serves titles, console system DLLs and +//! host binaries alike. This crate never modifies anything; patching lives in +//! `victory-loader`, which uses the raw offsets exported from [`layout`]. + +mod image; +pub mod implib; +pub mod layout; + +pub use image::{ + CodeViewInfo, ExportInfo, ImageInfo, ImportEntry, ImportModule, ImportSymbol, SectionInfo, + TlsInfo, +}; + +/// Errors produced while parsing an image or import library. +#[derive(Debug, thiserror::Error)] +pub enum PeError { + /// The file is a valid PE but not one we handle (e.g. 32-bit or ARM64). + #[error("unsupported image: {0}")] + Unsupported(String), + /// The file is truncated or internally inconsistent. + #[error("malformed image: {0}")] + Malformed(String), +} + +impl From for PeError { + fn from(e: object::read::Error) -> Self { + PeError::Malformed(e.to_string()) + } +} + +/// `IMAGE_FILE_MACHINE_AMD64`. +pub const MACHINE_AMD64: u16 = 0x8664; diff --git a/crates/victory-pipeline/Cargo.toml b/crates/victory-pipeline/Cargo.toml new file mode 100644 index 0000000..f5d5ccb --- /dev/null +++ b/crates/victory-pipeline/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "victory-pipeline" +description = "Offline conversion of user-supplied game data into host formats, with a content-addressed cache." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +victory-core.workspace = true +anyhow.workspace = true +blake3.workspace = true +tracing.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-pipeline/src/cache.rs b/crates/victory-pipeline/src/cache.rs new file mode 100644 index 0000000..1e4b7ec --- /dev/null +++ b/crates/victory-pipeline/src/cache.rs @@ -0,0 +1,130 @@ +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; + +use crate::Converter; + +/// Identifies one conversion result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct CacheKey(blake3::Hash); + +impl CacheKey { + pub fn new(converter: &dyn Converter, input: &[u8]) -> Self { + let mut h = blake3::Hasher::new(); + h.update(converter.id().as_bytes()); + h.update(&[0]); + h.update(&converter.version().to_le_bytes()); + h.update(input); + CacheKey(h.finalize()) + } + + pub fn to_hex(&self) -> String { + self.0.to_hex().to_string() + } +} + +/// Content-addressed store under the user's cache directory. +#[derive(Debug, Clone)] +pub struct Cache { + root: PathBuf, +} + +impl Cache { + /// Opens (creating) a cache at `root`. Refuses locations inside the repo. + pub fn open(root: impl Into) -> Result { + let root = root.into(); + victory_core::ensure_outside_repo(&root)?; + std::fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?; + Ok(Cache { root }) + } + + pub fn path_for(&self, key: &CacheKey) -> PathBuf { + let hex = key.to_hex(); + self.root.join(&hex[..2]).join(&hex[2..]) + } + + /// Returns the cached output for `input`, converting it first if needed. + pub fn get_or_convert(&self, converter: &dyn Converter, input: &[u8]) -> Result { + let key = CacheKey::new(converter, input); + let path = self.path_for(&key); + if path.is_file() { + tracing::trace!(converter = converter.id(), key = %key.to_hex(), "cache hit"); + return Ok(path); + } + let output = converter + .convert(input) + .with_context(|| format!("converter {} v{}", converter.id(), converter.version()))?; + let dir = path.parent().expect("hashed path has a parent"); + std::fs::create_dir_all(dir)?; + // Write-then-rename so readers never see partial output. + let tmp = tempfile_in(dir); + std::fs::write(&tmp, &output)?; + std::fs::rename(&tmp, &path)?; + Ok(path) + } +} + +fn tempfile_in(dir: &Path) -> PathBuf { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + dir.join(format!(".tmp-{}-{n}", std::process::id())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Upper { + version: u32, + runs: AtomicUsize, + } + + impl Converter for Upper { + fn id(&self) -> &'static str { + "test.upper" + } + fn version(&self) -> u32 { + self.version + } + fn convert(&self, input: &[u8]) -> Result> { + self.runs.fetch_add(1, Ordering::Relaxed); + Ok(input.to_ascii_uppercase()) + } + } + + #[test] + fn converts_once_then_hits() { + let tmp = tempfile::tempdir().unwrap(); + let cache = Cache::open(tmp.path().join("cache")).unwrap(); + let conv = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let a = cache.get_or_convert(&conv, b"abc").unwrap(); + let b = cache.get_or_convert(&conv, b"abc").unwrap(); + assert_eq!(a, b); + assert_eq!(std::fs::read(&a).unwrap(), b"ABC"); + assert_eq!(conv.runs.load(Ordering::Relaxed), 1); + } + + #[test] + fn version_bump_invalidates() { + let v1 = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let v2 = Upper { + version: 2, + runs: AtomicUsize::new(0), + }; + assert_ne!(CacheKey::new(&v1, b"x"), CacheKey::new(&v2, b"x")); + } + + #[test] + fn refuses_cache_inside_repo() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache"); + assert!(Cache::open(inside).is_err()); + } +} diff --git a/crates/victory-pipeline/src/lib.rs b/crates/victory-pipeline/src/lib.rs new file mode 100644 index 0000000..c417e5c --- /dev/null +++ b/crates/victory-pipeline/src/lib.rs @@ -0,0 +1,23 @@ +//! Offline conversion of the user's game data into host formats. +//! +//! Everything here runs on the user's machine, reads the user's files and +//! writes into the user's cache. Nothing produced here is ever committed: +//! derived data is still game data (docs/asset-policy.md). +//! +//! The unit of work is a [`Converter`]: bytes in, bytes out, deterministic. +//! Results are stored in a content-addressed [`Cache`] keyed by converter +//! id, converter version and input bytes, so re-running the pipeline after +//! a game update or a converter fix only redoes what changed. + +mod cache; + +pub use cache::{Cache, CacheKey}; + +/// A deterministic transformation of one input into one output. +pub trait Converter: Send + Sync { + /// Stable identifier, e.g. `"texture.detile"`. Part of the cache key. + fn id(&self) -> &'static str; + /// Bump whenever the output for a given input changes. + fn version(&self) -> u32; + fn convert(&self, input: &[u8]) -> anyhow::Result>; +} diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml new file mode 100644 index 0000000..d3f8c2c --- /dev/null +++ b/crates/victory-shader/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "victory-shader" +description = "Xbox shader containers (DXBC/DXIL + precompiled GFX10) to host shaders." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +thiserror.workspace = true +miniz_oxide.workspace = true + +[lints] +workspace = true diff --git a/crates/victory-shader/src/dxbc.rs b/crates/victory-shader/src/dxbc.rs new file mode 100644 index 0000000..605037f --- /dev/null +++ b/crates/victory-shader/src/dxbc.rs @@ -0,0 +1,179 @@ +//! The DXBC container: a header, then a table of FourCC-tagged parts. +//! +//! ```text +//! 0x00 "DXBC" +//! 0x04 digest[16] +//! 0x14 version major u16, minor u16 +//! 0x18 total size u32 +//! 0x1C part count u32 +//! 0x20 part offsets u32[count] +//! part: fourcc[4], size u32, data[size] +//! ``` + +use crate::ShaderError; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct FourCC(pub [u8; 4]); + +impl FourCC { + pub const DXIL: FourCC = FourCC(*b"DXIL"); + pub const STAT: FourCC = FourCC(*b"STAT"); + pub const RTS0: FourCC = FourCC(*b"RTS0"); + pub const PSV0: FourCC = FourCC(*b"PSV0"); + pub const ISG1: FourCC = FourCC(*b"ISG1"); + pub const OSG1: FourCC = FourCC(*b"OSG1"); + pub const SFI0: FourCC = FourCC(*b"SFI0"); + pub const HASH: FourCC = FourCC(*b"HASH"); + pub const ILDB: FourCC = FourCC(*b"ILDB"); + pub const ILDN: FourCC = FourCC(*b"ILDN"); +} + +impl std::fmt::Debug for FourCC { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self) + } +} + +impl std::fmt::Display for FourCC { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + for &b in &self.0 { + let c = if b.is_ascii_graphic() { b as char } else { '.' }; + write!(f, "{c}")?; + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy)] +pub struct Part<'a> { + pub fourcc: FourCC, + /// Offset of the part header within the container. + pub offset: usize, + pub data: &'a [u8], +} + +#[derive(Debug, Clone)] +pub struct Container<'a> { + pub digest: [u8; 16], + pub version: (u16, u16), + pub parts: Vec>, +} + +const HEADER_SIZE: usize = 0x20; +const MAX_PARTS: usize = 256; + +impl<'a> Container<'a> { + pub fn parse(data: &'a [u8]) -> Result { + if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" { + return Err(ShaderError::NotDxbc); + } + let digest = data[4..20].try_into().expect("16 bytes"); + let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?); + let total = u32_at(data, 0x18)? as usize; + if total > data.len() || total < HEADER_SIZE { + return Err(ShaderError::Malformed("container size disagrees with data")); + } + let data = &data[..total]; + let count = u32_at(data, 0x1C)? as usize; + if count > MAX_PARTS { + return Err(ShaderError::Malformed("implausible part count")); + } + let mut parts = Vec::with_capacity(count); + for i in 0..count { + let offset = u32_at(data, HEADER_SIZE + 4 * i)? as usize; + let fourcc = FourCC( + data.get(offset..offset + 4) + .ok_or(ShaderError::Malformed("part header out of bounds"))? + .try_into() + .expect("4 bytes"), + ); + let size = u32_at(data, offset + 4)? as usize; + let body = data + .get(offset + 8..offset + 8 + size) + .ok_or(ShaderError::Malformed("part data out of bounds"))?; + parts.push(Part { + fourcc, + offset, + data: body, + }); + } + Ok(Container { + digest, + version, + parts, + }) + } + + pub fn part(&self, fourcc: FourCC) -> Option<&Part<'a>> { + self.parts.iter().find(|p| p.fourcc == fourcc) + } +} + +pub(crate) fn u16_at(data: &[u8], at: usize) -> Result { + data.get(at..at + 2) + .map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes"))) + .ok_or(ShaderError::Malformed("truncated")) +} + +pub(crate) fn u32_at(data: &[u8], at: usize) -> Result { + data.get(at..at + 4) + .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes"))) + .ok_or(ShaderError::Malformed("truncated")) +} + +pub(crate) fn u64_at(data: &[u8], at: usize) -> Result { + data.get(at..at + 8) + .map(|b| u64::from_le_bytes(b.try_into().expect("8 bytes"))) + .ok_or(ShaderError::Malformed("truncated")) +} + +/// Builds a container from parts (test helper). +#[cfg(test)] +pub fn build(parts: &[(FourCC, &[u8])]) -> Vec { + let table = HEADER_SIZE + 4 * parts.len(); + let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); + let mut out = Vec::with_capacity(total); + out.extend_from_slice(b"DXBC"); + out.extend_from_slice(&[0; 16]); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&(total as u32).to_le_bytes()); + out.extend_from_slice(&(parts.len() as u32).to_le_bytes()); + let mut offset = table; + for (_, d) in parts { + out.extend_from_slice(&(offset as u32).to_le_bytes()); + offset += 8 + d.len(); + } + for (fourcc, d) in parts { + out.extend_from_slice(&fourcc.0); + out.extend_from_slice(&(d.len() as u32).to_le_bytes()); + out.extend_from_slice(d); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_parts() { + let bytes = build(&[(FourCC::SFI0, &[1, 2, 3, 4]), (FourCC::HASH, &[9; 20])]); + let c = Container::parse(&bytes).unwrap(); + assert_eq!(c.parts.len(), 2); + assert_eq!(c.part(FourCC::SFI0).unwrap().data, &[1, 2, 3, 4]); + assert_eq!(c.part(FourCC::HASH).unwrap().data.len(), 20); + assert!(c.part(FourCC::DXIL).is_none()); + } + + #[test] + fn rejects_bad_input() { + assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc); + let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]); + let last = bytes.len() - 1; + bytes[0x20] = 0xFF; // corrupt the first part offset + assert!(Container::parse(&bytes).is_err()); + bytes.truncate(last); + assert!(Container::parse(&bytes).is_err()); + } +} diff --git a/crates/victory-shader/src/dxil.rs b/crates/victory-shader/src/dxil.rs new file mode 100644 index 0000000..8c7a71c --- /dev/null +++ b/crates/victory-shader/src/dxil.rs @@ -0,0 +1,211 @@ +//! The DXIL program inside a container's `DXIL` (or `STAT`) part. +//! +//! ```text +//! 0x00 program version u32 (kind << 16 | major << 4 | minor) +//! 0x04 size in dwords u32 +//! 0x08 "DXIL" <- bitcode offset is relative to here +//! 0x0C dxil version u32 +//! 0x10 bitcode offset u32 (16 in standard PC DXIL) +//! 0x14 bitcode size u32 +//! ``` + +use crate::ShaderError; +use crate::dxbc::u32_at; + +const LLVM_BITCODE_MAGIC: [u8; 4] = [0x42, 0x43, 0xC0, 0xDE]; +#[cfg(test)] +const STANDARD_BITCODE_OFFSET: u32 = 16; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ShaderKind { + Pixel, + Vertex, + Geometry, + Hull, + Domain, + Compute, + Library, + RayGeneration, + Intersection, + AnyHit, + ClosestHit, + Miss, + Callable, + Mesh, + Amplification, + Node, + Unknown(u16), +} + +impl ShaderKind { + fn from_raw(v: u16) -> Self { + use ShaderKind::*; + match v { + 0 => Pixel, + 1 => Vertex, + 2 => Geometry, + 3 => Hull, + 4 => Domain, + 5 => Compute, + 6 => Library, + 7 => RayGeneration, + 8 => Intersection, + 9 => AnyHit, + 10 => ClosestHit, + 11 => Miss, + 12 => Callable, + 13 => Mesh, + 14 => Amplification, + 15 => Node, + other => Unknown(other), + } + } +} + +#[derive(Debug, Clone)] +pub struct DxilProgram<'a> { + pub kind: ShaderKind, + pub shader_model: (u8, u8), + pub dxil_version: u32, + /// LLVM bitcode (starts with `BC C0 DE`). + pub bitcode: &'a [u8], + /// Bytes between the bitcode header and the bitcode. Empty on PC. + pub prefix: &'a [u8], + /// Bytes after the bitcode, up to the program size. Empty on PC. + pub trailer: &'a [u8], +} + +/// Xbox additions recognised around the bitcode. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct XboxExtras { + /// The prefix starts with an `XDAT` table. + pub xdat: bool, + /// The trailer contains an `xbop` blob (compiler options). + pub xbop: bool, +} + +impl<'a> DxilProgram<'a> { + pub fn parse(part: &'a [u8]) -> Result { + let version = u32_at(part, 0)?; + let size = (u32_at(part, 4)? as usize) + .checked_mul(4) + .filter(|&s| s <= part.len() && s >= 24) + .ok_or(ShaderError::Malformed( + "program size disagrees with part size", + ))?; + let part = &part[..size]; + if part.get(8..12) != Some(b"DXIL") { + return Err(ShaderError::Malformed("missing DXIL magic")); + } + let dxil_version = u32_at(part, 12)?; + let offset = u32_at(part, 16)?; + let len = u32_at(part, 20)? as usize; + let start = 8 + offset as usize; + let bitcode = part + .get(start..start + len) + .ok_or(ShaderError::Malformed("bitcode out of bounds"))?; + if bitcode.get(0..4) != Some(&LLVM_BITCODE_MAGIC) { + return Err(ShaderError::Malformed("bitcode lacks LLVM magic")); + } + let prefix = part + .get(24..start) + .ok_or(ShaderError::Malformed("bitcode offset too small"))?; + Ok(DxilProgram { + kind: ShaderKind::from_raw((version >> 16) as u16), + shader_model: (((version >> 4) & 0xF) as u8, (version & 0xF) as u8), + dxil_version, + bitcode, + prefix, + trailer: &part[start + len..], + }) + } + + /// True for a program laid out exactly like PC DXIL. + pub fn is_standard_layout(&self) -> bool { + self.prefix.is_empty() && self.trailer.is_empty() + } + + pub fn xbox_extras(&self) -> XboxExtras { + XboxExtras { + xdat: self.prefix.starts_with(b"XDAT"), + xbop: self.trailer.windows(4).any(|w| w == b"xbop"), + } + } +} + +/// Builds a standard PC-layout program around `bitcode` (test helper). +#[cfg(test)] +pub fn build_standard(kind: u16, sm: (u8, u8), dxil_version: u32, bitcode: &[u8]) -> Vec { + let mut out = Vec::new(); + let version = (u32::from(kind) << 16) | (u32::from(sm.0) << 4) | u32::from(sm.1); + let padded = bitcode.len().next_multiple_of(4); + let size_dwords = (24 + padded) / 4; + out.extend_from_slice(&version.to_le_bytes()); + out.extend_from_slice(&(size_dwords as u32).to_le_bytes()); + out.extend_from_slice(b"DXIL"); + out.extend_from_slice(&dxil_version.to_le_bytes()); + out.extend_from_slice(&STANDARD_BITCODE_OFFSET.to_le_bytes()); + out.extend_from_slice(&(bitcode.len() as u32).to_le_bytes()); + out.extend_from_slice(bitcode); + out.resize(24 + padded, 0); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fake_bitcode() -> Vec { + let mut b = LLVM_BITCODE_MAGIC.to_vec(); + b.extend_from_slice(&[0xAA; 12]); + b + } + + #[test] + fn parses_standard_layout() { + let bytes = build_standard(0, (6, 0), 0x100, &fake_bitcode()); + let p = DxilProgram::parse(&bytes).unwrap(); + assert_eq!(p.kind, ShaderKind::Pixel); + assert_eq!(p.shader_model, (6, 0)); + assert!(p.is_standard_layout()); + assert_eq!(p.xbox_extras(), XboxExtras::default()); + } + + #[test] + fn detects_xbox_layout() { + // Xbox layout: XDAT table before the bitcode, xbop blob after it. + let bitcode = fake_bitcode(); + let xdat = b"XDAT\x01\x00\x00\x00"; + let trailer = b"xbop\x02\x00\x00\x00"; + let mut bytes = Vec::new(); + let size = 24 + xdat.len() + bitcode.len() + trailer.len(); + bytes.extend_from_slice(&((5u32 << 16) | 0x65).to_le_bytes()); // cs_6_5 + bytes.extend_from_slice(&((size / 4) as u32).to_le_bytes()); + bytes.extend_from_slice(b"DXIL"); + bytes.extend_from_slice(&0x105u32.to_le_bytes()); + bytes.extend_from_slice(&(16 + xdat.len() as u32).to_le_bytes()); + bytes.extend_from_slice(&(bitcode.len() as u32).to_le_bytes()); + bytes.extend_from_slice(xdat); + bytes.extend_from_slice(&bitcode); + bytes.extend_from_slice(trailer); + + let p = DxilProgram::parse(&bytes).unwrap(); + assert_eq!(p.kind, ShaderKind::Compute); + assert_eq!(p.shader_model, (6, 5)); + assert!(!p.is_standard_layout()); + assert_eq!( + p.xbox_extras(), + XboxExtras { + xdat: true, + xbop: true + } + ); + assert_eq!(p.bitcode, &bitcode[..]); + } + + #[test] + fn rejects_missing_bitcode_magic() { + let bytes = build_standard(0, (6, 0), 0x100, &[0u8; 16]); + assert!(DxilProgram::parse(&bytes).is_err()); + } +} diff --git a/crates/victory-shader/src/gfx10/mod.rs b/crates/victory-shader/src/gfx10/mod.rs new file mode 100644 index 0000000..d33f3f1 --- /dev/null +++ b/crates/victory-shader/src/gfx10/mod.rs @@ -0,0 +1,447 @@ +//! GFX10 machine code: instruction boundaries, encodings and opcodes. +//! +//! Instructions are found by following control flow from offset 0, not by a +//! linear sweep: compilers place data (constant tables) in the code region +//! after the end of the program. Operand fields are not decoded yet; each +//! instruction keeps its raw dwords. +//! +//! Encodings by the top bits of the first dword: +//! +//! ```text +//! 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC +//! 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP +//! 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH +//! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP +//! ``` + +mod opcodes; + +use std::collections::BTreeMap; + +use crate::ShaderError; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Encoding { + Sop2, + Sopk, + Sop1, + Sopc, + Sopp, + Smem, + Vop2, + Vop1, + Vopc, + Vop3, + Vop3p, + Vintrp, + Ds, + Mubuf, + Mtbuf, + Mimg, + Exp, + Flat, + Global, + Scratch, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Instruction { + /// Byte offset in the program. + pub offset: usize, + pub encoding: Encoding, + pub opcode: u16, + /// Every dword of the instruction, including literals and extra dwords. + pub words: Vec, +} + +impl Instruction { + /// AMD's name for the opcode, if it is in our table. + pub fn name(&self) -> Option<&'static str> { + name(self.encoding, self.opcode) + } +} + +/// Decodes every instruction reachable from offset 0, sorted by offset. +pub fn decode(code: &[u8]) -> Result, ShaderError> { + if !code.len().is_multiple_of(4) { + return Err(isa(code.len(), "code size is not a multiple of 4")); + } + let mut found = BTreeMap::new(); + let mut pending = vec![0usize]; + while let Some(mut offset) = pending.pop() { + while !found.contains_key(&offset) { + let inst = instruction(code, offset)?; + let next = offset + 4 * inst.words.len(); + let flow = match flow(&inst, next, code.len())? { + Flow::Stop if inst.name() == Some("s_setpc_b64") => { + far_jump(&found, &inst, code.len())?.map_or(Flow::Stop, Flow::Jump) + } + flow => flow, + }; + found.insert(offset, inst); + match flow { + Flow::Next => offset = next, + Flow::Stop => break, + Flow::Jump(target) => offset = target, + Flow::Branch(target) => { + pending.push(target); + offset = next; + } + } + } + } + let list: Vec = found.into_values().collect(); + if let Some(w) = list + .windows(2) + .find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset) + { + return Err(isa(w[1].offset, "a branch lands inside an instruction")); + } + Ok(list) +} + +enum Flow { + Next, + Stop, + Jump(usize), + Branch(usize), +} + +fn flow(inst: &Instruction, next: usize, len: usize) -> Result { + let target = || { + let delta = 4 * i64::from(inst.words[0] as u16 as i16); + usize::try_from(next as i64 + delta) + .ok() + .filter(|&t| t < len) + .ok_or(isa(inst.offset, "branch target outside the code")) + }; + Ok(match (inst.encoding, inst.name().unwrap_or("")) { + ( + Encoding::Sopp, + "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" | "s_code_end", + ) => Flow::Stop, + (Encoding::Sopp, "s_branch") => Flow::Jump(target()?), + (Encoding::Sopp, name) if name.starts_with("s_cbranch_") => Flow::Branch(target()?), + (Encoding::Sopk, "s_call_b64") => Flow::Branch(target()?), + // Indirect jump; `decode` resolves the compiler's far-jump form. + (Encoding::Sop1, "s_setpc_b64") => Flow::Stop, + _ => Flow::Next, + }) +} + +/// Resolves the far jump compilers emit beyond the reach of a branch offset: +/// `s_getpc_b64 s[n:n+1]`, `s_add_u32|s_sub_u32 sn, sn, literal`, a carry +/// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line +/// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next +/// merged stage through registers) gives `None`. +fn far_jump( + found: &BTreeMap, + setpc: &Instruction, + len: usize, +) -> Result, ShaderError> { + let n = setpc.words[0] & 0xFF; + let mut delta = None; + let mut at = setpc.offset; + for _ in 0..4 { + let Some((_, prev)) = found.range(..at).next_back() else { + break; + }; + if prev.offset + 4 * prev.words.len() != at { + break; + } + let w = prev.words[0]; + let (sdst, ssrc0, ssrc1) = ((w >> 16) & 0x7F, w & 0xFF, (w >> 8) & 0xFF); + match (prev.encoding, prev.name()) { + (Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32"))) + if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() => + { + let literal = i64::from(prev.words[1]); + delta = Some(if op == "s_add_u32" { literal } else { -literal }); + } + (Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => { + let Some(delta) = delta else { break }; + // s_getpc_b64 yields the address of the instruction after it. + return usize::try_from(prev.offset as i64 + 4 + delta) + .ok() + .filter(|&t| t < len) + .map(Some) + .ok_or(isa(setpc.offset, "far jump target outside the code")); + } + _ => {} + } + at = prev.offset; + } + Ok(None) +} + +fn instruction(code: &[u8], offset: usize) -> Result { + let word = |i: usize| { + code.get(offset + 4 * i..offset + 4 * i + 4) + .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes"))) + .ok_or(isa(offset, "instruction runs past the end of the code")) + }; + let w = word(0)?; + let (encoding, opcode, len) = if w >> 31 == 0 { + let src0 = w & 0x1FF; + // Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive. + let extra = usize::from(matches!(src0, 0xFF | 0xF9 | 0xFA | 0xE9 | 0xEA)); + match w >> 25 { + 0x3F => (Encoding::Vop1, (w >> 9) & 0xFF, 1 + extra), + 0x3E => (Encoding::Vopc, (w >> 17) & 0xFF, 1 + extra), + op => { + let mk_ak = name(Encoding::Vop2, op as u16).is_some_and(|n| { + matches!( + n, + "v_madmk_f32" + | "v_madak_f32" + | "v_fmamk_f32" + | "v_fmaak_f32" + | "v_madmk_f16" + | "v_madak_f16" + | "v_fmamk_f16" + | "v_fmaak_f16" + ) + }); + (Encoding::Vop2, op, 1 + extra.max(usize::from(mk_ak))) + } + } + } else if w >> 30 == 0b10 { + let literal = |srcs: &[u32]| 1 + usize::from(srcs.contains(&0xFF)); + match w >> 23 { + 0x17D => (Encoding::Sop1, (w >> 8) & 0xFF, literal(&[w & 0xFF])), + 0x17E => ( + Encoding::Sopc, + (w >> 16) & 0x7F, + literal(&[w & 0xFF, (w >> 8) & 0xFF]), + ), + 0x17F => (Encoding::Sopp, (w >> 16) & 0x7F, 1), + _ if w >> 28 == 0b1011 => { + let op = (w >> 23) & 0x1F; + let imm32 = name(Encoding::Sopk, op as u16) == Some("s_setreg_imm32_b32"); + (Encoding::Sopk, op, 1 + usize::from(imm32)) + } + _ => ( + Encoding::Sop2, + (w >> 23) & 0x7F, + literal(&[w & 0xFF, (w >> 8) & 0xFF]), + ), + } + } else { + let vop3 = + |w1: u32| 2 + usize::from([w1, w1 >> 9, w1 >> 18].iter().any(|s| s & 0x1FF == 0xFF)); + match w >> 26 { + 0x32 => (Encoding::Vintrp, (w >> 16) & 0x3, 1), + 0x33 => (Encoding::Vop3p, (w >> 16) & 0x7F, vop3(word(1)?)), + 0x35 => (Encoding::Vop3, (w >> 16) & 0x3FF, vop3(word(1)?)), + 0x36 => (Encoding::Ds, (w >> 18) & 0xFF, 2), + 0x37 => { + let encoding = match (w >> 14) & 3 { + 0 => Encoding::Flat, + 1 => Encoding::Scratch, + 2 => Encoding::Global, + _ => return Err(isa(offset, "reserved FLAT segment")), + }; + (encoding, (w >> 18) & 0x7F, 2) + } + 0x38 => (Encoding::Mubuf, (w >> 18) & 0x7F | (w >> 25 & 1) << 7, 2), + 0x3A => ( + Encoding::Mtbuf, + (w >> 16) & 0x7 | (word(1)? >> 21 & 1) << 3, + 2, + ), + // Bits 2:1 count extra dwords of non-sequential address registers. + 0x3C => ( + Encoding::Mimg, + (w >> 18) & 0x7F | (w & 1) << 7, + 2 + (w as usize >> 1 & 3), + ), + 0x3D => (Encoding::Smem, (w >> 18) & 0xFF, 2), + 0x3E => (Encoding::Exp, 0, 2), + _ => return Err(isa(offset, "unknown encoding")), + } + }; + Ok(Instruction { + offset, + encoding, + opcode: opcode as u16, + words: (0..len).map(word).collect::>()?, + }) +} + +fn name(encoding: Encoding, opcode: u16) -> Option<&'static str> { + use opcodes as t; + let (table, op) = match encoding { + Encoding::Sop2 => (t::SOP2, opcode), + Encoding::Sopk => (t::SOPK, opcode), + Encoding::Sop1 => (t::SOP1, opcode), + Encoding::Sopc => (t::SOPC, opcode), + Encoding::Sopp => (t::SOPP, opcode), + Encoding::Smem => (t::SMEM, opcode), + Encoding::Vop2 => (t::VOP2, opcode), + Encoding::Vop1 => (t::VOP1, opcode), + Encoding::Vopc => (t::VOPC, opcode), + // VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases. + Encoding::Vop3 => match opcode { + 0x000..0x100 => (t::VOPC, opcode), + 0x100..0x140 => (t::VOP2, opcode - 0x100), + 0x180..0x200 => (t::VOP1, opcode - 0x180), + _ => (t::VOP3, opcode), + }, + Encoding::Vop3p => (t::VOP3P, opcode), + Encoding::Vintrp => (t::VINTRP, opcode), + Encoding::Ds => (t::DS, opcode), + Encoding::Mubuf => (t::MUBUF, opcode), + Encoding::Mtbuf => (t::MTBUF, opcode), + Encoding::Mimg => (t::MIMG, opcode), + Encoding::Exp => return Some("exp"), + Encoding::Flat => (t::FLAT, opcode), + Encoding::Global => (t::GLOBAL, opcode), + Encoding::Scratch => (t::SCRATCH, opcode), + }; + table + .binary_search_by_key(&op, |&(o, _)| o) + .ok() + .map(|i| table[i].1) +} + +fn isa(offset: usize, reason: &'static str) -> ShaderError { + ShaderError::Isa { offset, reason } +} + +#[cfg(test)] +mod tests { + use super::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + /// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction. + const fn sopp(op: u32, simm16: i16) -> u32 { + 0xBF80_0000 | op << 16 | simm16 as u16 as u32 + } + + fn bytes(words: &[u32]) -> Vec { + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + fn summary(code: &[u32]) -> Vec<(usize, usize, &'static str)> { + decode(&bytes(code)) + .unwrap() + .iter() + .map(|i| (i.offset, i.words.len(), i.name().unwrap_or("?"))) + .collect() + } + + #[test] + fn tables_are_sorted() { + for t in [ + opcodes::SOP2, + opcodes::SOPK, + opcodes::SOP1, + opcodes::SOPC, + opcodes::SOPP, + opcodes::SMEM, + opcodes::VOP2, + opcodes::VOP1, + opcodes::VOPC, + opcodes::VOP3, + opcodes::VOP3P, + opcodes::VINTRP, + opcodes::DS, + opcodes::MUBUF, + opcodes::MTBUF, + opcodes::MIMG, + opcodes::FLAT, + opcodes::GLOBAL, + opcodes::SCRATCH, + ] { + assert!(t.windows(2).all(|w| w[0].0 < w[1].0)); + } + } + + #[test] + fn lengths_and_names() { + let code = [ + 0xBE80_03FF, + 0x3F80_0000, // s_mov_b32 s0, literal + 0x0600_0000, // v_add_f32 v0, s0, v0 + 0xD54B_0000, + 0x03FE_0000, + 0x4000_0000, // v_fma_f32 with a literal src2 + 0xF080_0F0A, + 0, + 0, // image_sample (2D) with one extra address dword + 0xF800_080F, + 0, // exp + S_ENDPGM, + ]; + assert_eq!( + summary(&code), + [ + (0, 2, "s_mov_b32"), + (8, 1, "v_add_f32"), + (12, 3, "v_fma_f32"), + (24, 3, "image_sample"), + (36, 2, "exp"), + (44, 1, "s_endpgm"), + ] + ); + } + + #[test] + fn follows_branches_and_skips_data() { + let code = [ + sopp(0x04, 1), // s_cbranch_scc0 -> 8 + sopp(0x02, 1), // s_branch -> 12 + S_ENDPGM, + S_ENDPGM, + S_ENDPGM, // data follows the program end + 0xFFFF_FFFF, + ]; + let found: Vec<_> = summary(&code).iter().map(|i| i.0).collect(); + assert_eq!(found, [0, 4, 8, 12]); + } + + #[test] + fn follows_far_jumps() { + let code = [ + 0xBE88_1F00, // s_getpc_b64 s[8:9] + 0x8008_FF08, + 20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24 + 0x8209_8009, // s_addc_u32 s9, s9, 0 + 0xBE80_2008, // s_setpc_b64 s[8:9] + 0xFFFF_FFFF, // not code + S_ENDPGM, + ]; + let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect(); + assert_eq!( + found, + [ + (0, "s_getpc_b64"), + (4, "s_add_u32"), + (12, "s_addc_u32"), + (16, "s_setpc_b64"), + (24, "s_endpgm"), + ] + ); + // Through other registers (a handover to another stage): the path ends. + assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1); + } + + #[test] + fn rejects_bad_code() { + assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4"); + assert!( + decode(&bytes(&[sopp(0x02, 100)])).is_err(), + "branch out of range" + ); + assert!( + decode(&bytes(&[0xBE80_03FF])).is_err(), + "literal past the end" + ); + assert!( + decode(&bytes(&[0xE400_0000, 0])).is_err(), + "unknown encoding" + ); + // s_cbranch_scc0 into the literal of the s_mov_b32 at 4. + assert!(decode(&bytes(&[sopp(0x04, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM])).is_err()); + } +} diff --git a/crates/victory-shader/src/gfx10/opcodes.rs b/crates/victory-shader/src/gfx10/opcodes.rs new file mode 100644 index 0000000..18dac4f --- /dev/null +++ b/crates/victory-shader/src/gfx10/opcodes.rs @@ -0,0 +1,1315 @@ +// GFX10 opcode names, generated from Mesa's src/amd/compiler/aco_opcodes.py +// (tag mesa-22.3.0, GFX10 column), which carries this notice: +// +// Copyright (c) 2018 Valve Corporation +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice (including the next +// paragraph) shall be included in all copies or substantial portions of the +// Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. +// +// Each table is sorted by opcode. VOP3 holds only VOP3-only opcodes; VOP3 +// encodings of VOPC/VOP2/VOP1 ops (0x000-0x13f, 0x180-0x1ff) use those tables. + +pub(super) const SOP2: &[(u16, &str)] = &[ + (0x000, "s_add_u32"), + (0x001, "s_sub_u32"), + (0x002, "s_add_i32"), + (0x003, "s_sub_i32"), + (0x004, "s_addc_u32"), + (0x005, "s_subb_u32"), + (0x006, "s_min_i32"), + (0x007, "s_min_u32"), + (0x008, "s_max_i32"), + (0x009, "s_max_u32"), + (0x00a, "s_cselect_b32"), + (0x00b, "s_cselect_b64"), + (0x00e, "s_and_b32"), + (0x00f, "s_and_b64"), + (0x010, "s_or_b32"), + (0x011, "s_or_b64"), + (0x012, "s_xor_b32"), + (0x013, "s_xor_b64"), + (0x014, "s_andn2_b32"), + (0x015, "s_andn2_b64"), + (0x016, "s_orn2_b32"), + (0x017, "s_orn2_b64"), + (0x018, "s_nand_b32"), + (0x019, "s_nand_b64"), + (0x01a, "s_nor_b32"), + (0x01b, "s_nor_b64"), + (0x01c, "s_xnor_b32"), + (0x01d, "s_xnor_b64"), + (0x01e, "s_lshl_b32"), + (0x01f, "s_lshl_b64"), + (0x020, "s_lshr_b32"), + (0x021, "s_lshr_b64"), + (0x022, "s_ashr_i32"), + (0x023, "s_ashr_i64"), + (0x024, "s_bfm_b32"), + (0x025, "s_bfm_b64"), + (0x026, "s_mul_i32"), + (0x027, "s_bfe_u32"), + (0x028, "s_bfe_i32"), + (0x029, "s_bfe_u64"), + (0x02a, "s_bfe_i64"), + (0x02c, "s_absdiff_i32"), + (0x02e, "s_lshl1_add_u32"), + (0x02f, "s_lshl2_add_u32"), + (0x030, "s_lshl3_add_u32"), + (0x031, "s_lshl4_add_u32"), + (0x032, "s_pack_ll_b32_b16"), + (0x033, "s_pack_lh_b32_b16"), + (0x034, "s_pack_hh_b32_b16"), + (0x035, "s_mul_hi_u32"), + (0x036, "s_mul_hi_i32"), +]; + +pub(super) const SOPK: &[(u16, &str)] = &[ + (0x000, "s_movk_i32"), + (0x001, "s_version"), + (0x002, "s_cmovk_i32"), + (0x003, "s_cmpk_eq_i32"), + (0x004, "s_cmpk_lg_i32"), + (0x005, "s_cmpk_gt_i32"), + (0x006, "s_cmpk_ge_i32"), + (0x007, "s_cmpk_lt_i32"), + (0x008, "s_cmpk_le_i32"), + (0x009, "s_cmpk_eq_u32"), + (0x00a, "s_cmpk_lg_u32"), + (0x00b, "s_cmpk_gt_u32"), + (0x00c, "s_cmpk_ge_u32"), + (0x00d, "s_cmpk_lt_u32"), + (0x00e, "s_cmpk_le_u32"), + (0x00f, "s_addk_i32"), + (0x010, "s_mulk_i32"), + (0x012, "s_getreg_b32"), + (0x013, "s_setreg_b32"), + (0x015, "s_setreg_imm32_b32"), + (0x016, "s_call_b64"), + (0x017, "s_waitcnt_vscnt"), + (0x018, "s_waitcnt_vmcnt"), + (0x019, "s_waitcnt_expcnt"), + (0x01a, "s_waitcnt_lgkmcnt"), + (0x01b, "s_subvector_loop_begin"), + (0x01c, "s_subvector_loop_end"), +]; + +pub(super) const SOP1: &[(u16, &str)] = &[ + (0x003, "s_mov_b32"), + (0x004, "s_mov_b64"), + (0x005, "s_cmov_b32"), + (0x006, "s_cmov_b64"), + (0x007, "s_not_b32"), + (0x008, "s_not_b64"), + (0x009, "s_wqm_b32"), + (0x00a, "s_wqm_b64"), + (0x00b, "s_brev_b32"), + (0x00c, "s_brev_b64"), + (0x00d, "s_bcnt0_i32_b32"), + (0x00e, "s_bcnt0_i32_b64"), + (0x00f, "s_bcnt1_i32_b32"), + (0x010, "s_bcnt1_i32_b64"), + (0x011, "s_ff0_i32_b32"), + (0x012, "s_ff0_i32_b64"), + (0x013, "s_ff1_i32_b32"), + (0x014, "s_ff1_i32_b64"), + (0x015, "s_flbit_i32_b32"), + (0x016, "s_flbit_i32_b64"), + (0x017, "s_flbit_i32"), + (0x018, "s_flbit_i32_i64"), + (0x019, "s_sext_i32_i8"), + (0x01a, "s_sext_i32_i16"), + (0x01b, "s_bitset0_b32"), + (0x01c, "s_bitset0_b64"), + (0x01d, "s_bitset1_b32"), + (0x01e, "s_bitset1_b64"), + (0x01f, "s_getpc_b64"), + (0x020, "s_setpc_b64"), + (0x021, "s_swappc_b64"), + (0x022, "s_rfe_b64"), + (0x024, "s_and_saveexec_b64"), + (0x025, "s_or_saveexec_b64"), + (0x026, "s_xor_saveexec_b64"), + (0x027, "s_andn2_saveexec_b64"), + (0x028, "s_orn2_saveexec_b64"), + (0x029, "s_nand_saveexec_b64"), + (0x02a, "s_nor_saveexec_b64"), + (0x02b, "s_xnor_saveexec_b64"), + (0x02c, "s_quadmask_b32"), + (0x02d, "s_quadmask_b64"), + (0x02e, "s_movrels_b32"), + (0x02f, "s_movrels_b64"), + (0x030, "s_movreld_b32"), + (0x031, "s_movreld_b64"), + (0x034, "s_abs_i32"), + (0x035, "s_mov_fed_b32"), + (0x037, "s_andn1_saveexec_b64"), + (0x038, "s_orn1_saveexec_b64"), + (0x039, "s_andn1_wrexec_b64"), + (0x03a, "s_andn2_wrexec_b64"), + (0x03b, "s_bitreplicate_b64_b32"), + (0x03c, "s_and_saveexec_b32"), + (0x03d, "s_or_saveexec_b32"), + (0x03e, "s_xor_saveexec_b32"), + (0x03f, "s_andn2_saveexec_b32"), + (0x040, "s_orn2_saveexec_b32"), + (0x041, "s_nand_saveexec_b32"), + (0x042, "s_nor_saveexec_b32"), + (0x043, "s_xnor_saveexec_b32"), + (0x044, "s_andn1_saveexec_b32"), + (0x045, "s_orn1_saveexec_b32"), + (0x046, "s_andn1_wrexec_b32"), + (0x047, "s_andn2_wrexec_b32"), + (0x049, "s_movrelsd_2_b32"), +]; + +pub(super) const SOPC: &[(u16, &str)] = &[ + (0x000, "s_cmp_eq_i32"), + (0x001, "s_cmp_lg_i32"), + (0x002, "s_cmp_gt_i32"), + (0x003, "s_cmp_ge_i32"), + (0x004, "s_cmp_lt_i32"), + (0x005, "s_cmp_le_i32"), + (0x006, "s_cmp_eq_u32"), + (0x007, "s_cmp_lg_u32"), + (0x008, "s_cmp_gt_u32"), + (0x009, "s_cmp_ge_u32"), + (0x00a, "s_cmp_lt_u32"), + (0x00b, "s_cmp_le_u32"), + (0x00c, "s_bitcmp0_b32"), + (0x00d, "s_bitcmp1_b32"), + (0x00e, "s_bitcmp0_b64"), + (0x00f, "s_bitcmp1_b64"), + (0x012, "s_cmp_eq_u64"), + (0x013, "s_cmp_lg_u64"), +]; + +pub(super) const SOPP: &[(u16, &str)] = &[ + (0x000, "s_nop"), + (0x001, "s_endpgm"), + (0x002, "s_branch"), + (0x003, "s_wakeup"), + (0x004, "s_cbranch_scc0"), + (0x005, "s_cbranch_scc1"), + (0x006, "s_cbranch_vccz"), + (0x007, "s_cbranch_vccnz"), + (0x008, "s_cbranch_execz"), + (0x009, "s_cbranch_execnz"), + (0x00a, "s_barrier"), + (0x00b, "s_setkill"), + (0x00c, "s_waitcnt"), + (0x00d, "s_sethalt"), + (0x00e, "s_sleep"), + (0x00f, "s_setprio"), + (0x010, "s_sendmsg"), + (0x011, "s_sendmsghalt"), + (0x012, "s_trap"), + (0x013, "s_icache_inv"), + (0x014, "s_incperflevel"), + (0x015, "s_decperflevel"), + (0x016, "s_ttracedata"), + (0x017, "s_cbranch_cdbgsys"), + (0x018, "s_cbranch_cdbguser"), + (0x019, "s_cbranch_cdbgsys_or_user"), + (0x01a, "s_cbranch_cdbgsys_and_user"), + (0x01b, "s_endpgm_saved"), + (0x01e, "s_endpgm_ordered_ps_done"), + (0x01f, "s_code_end"), + (0x020, "s_inst_prefetch"), + (0x021, "s_clause"), + (0x022, "s_wait_idle"), + (0x023, "s_waitcnt_depctr"), + (0x024, "s_round_mode"), + (0x025, "s_denorm_mode"), + (0x026, "s_ttracedata_imm"), +]; + +pub(super) const SMEM: &[(u16, &str)] = &[ + (0x000, "s_load_dword"), + (0x001, "s_load_dwordx2"), + (0x002, "s_load_dwordx4"), + (0x003, "s_load_dwordx8"), + (0x004, "s_load_dwordx16"), + (0x005, "s_scratch_load_dword"), + (0x006, "s_scratch_load_dwordx2"), + (0x007, "s_scratch_load_dwordx4"), + (0x008, "s_buffer_load_dword"), + (0x009, "s_buffer_load_dwordx2"), + (0x00a, "s_buffer_load_dwordx4"), + (0x00b, "s_buffer_load_dwordx8"), + (0x00c, "s_buffer_load_dwordx16"), + (0x010, "s_store_dword"), + (0x011, "s_store_dwordx2"), + (0x012, "s_store_dwordx4"), + (0x015, "s_scratch_store_dword"), + (0x016, "s_scratch_store_dwordx2"), + (0x017, "s_scratch_store_dwordx4"), + (0x018, "s_buffer_store_dword"), + (0x019, "s_buffer_store_dwordx2"), + (0x01a, "s_buffer_store_dwordx4"), + (0x01f, "s_gl1_inv"), + (0x020, "s_dcache_inv"), + (0x021, "s_dcache_wb"), + (0x024, "s_memtime"), + (0x025, "s_memrealtime"), + (0x026, "s_atc_probe"), + (0x027, "s_atc_probe_buffer"), + (0x028, "s_dcache_discard"), + (0x029, "s_dcache_discard_x2"), + (0x02a, "s_get_waveid_in_workgroup"), + (0x040, "s_buffer_atomic_swap"), + (0x041, "s_buffer_atomic_cmpswap"), + (0x042, "s_buffer_atomic_add"), + (0x043, "s_buffer_atomic_sub"), + (0x044, "s_buffer_atomic_smin"), + (0x045, "s_buffer_atomic_umin"), + (0x046, "s_buffer_atomic_smax"), + (0x047, "s_buffer_atomic_umax"), + (0x048, "s_buffer_atomic_and"), + (0x049, "s_buffer_atomic_or"), + (0x04a, "s_buffer_atomic_xor"), + (0x04b, "s_buffer_atomic_inc"), + (0x04c, "s_buffer_atomic_dec"), + (0x060, "s_buffer_atomic_swap_x2"), + (0x061, "s_buffer_atomic_cmpswap_x2"), + (0x062, "s_buffer_atomic_add_x2"), + (0x063, "s_buffer_atomic_sub_x2"), + (0x064, "s_buffer_atomic_smin_x2"), + (0x065, "s_buffer_atomic_umin_x2"), + (0x066, "s_buffer_atomic_smax_x2"), + (0x067, "s_buffer_atomic_umax_x2"), + (0x068, "s_buffer_atomic_and_x2"), + (0x069, "s_buffer_atomic_or_x2"), + (0x06a, "s_buffer_atomic_xor_x2"), + (0x06b, "s_buffer_atomic_inc_x2"), + (0x06c, "s_buffer_atomic_dec_x2"), + (0x080, "s_atomic_swap"), + (0x081, "s_atomic_cmpswap"), + (0x082, "s_atomic_add"), + (0x083, "s_atomic_sub"), + (0x084, "s_atomic_smin"), + (0x085, "s_atomic_umin"), + (0x086, "s_atomic_smax"), + (0x087, "s_atomic_umax"), + (0x088, "s_atomic_and"), + (0x089, "s_atomic_or"), + (0x08a, "s_atomic_xor"), + (0x08b, "s_atomic_inc"), + (0x08c, "s_atomic_dec"), + (0x0a0, "s_atomic_swap_x2"), + (0x0a1, "s_atomic_cmpswap_x2"), + (0x0a2, "s_atomic_add_x2"), + (0x0a3, "s_atomic_sub_x2"), + (0x0a4, "s_atomic_smin_x2"), + (0x0a5, "s_atomic_umin_x2"), + (0x0a6, "s_atomic_smax_x2"), + (0x0a7, "s_atomic_umax_x2"), + (0x0a8, "s_atomic_and_x2"), + (0x0a9, "s_atomic_or_x2"), + (0x0aa, "s_atomic_xor_x2"), + (0x0ab, "s_atomic_inc_x2"), + (0x0ac, "s_atomic_dec_x2"), +]; + +pub(super) const VOP2: &[(u16, &str)] = &[ + (0x001, "v_cndmask_b32"), + (0x002, "v_dot2c_f32_f16"), + (0x003, "v_add_f32"), + (0x004, "v_sub_f32"), + (0x005, "v_subrev_f32"), + (0x006, "v_mac_legacy_f32"), + (0x007, "v_mul_legacy_f32"), + (0x008, "v_mul_f32"), + (0x009, "v_mul_i32_i24"), + (0x00a, "v_mul_hi_i32_i24"), + (0x00b, "v_mul_u32_u24"), + (0x00c, "v_mul_hi_u32_u24"), + (0x00d, "v_dot4c_i32_i8"), + (0x00f, "v_min_f32"), + (0x010, "v_max_f32"), + (0x011, "v_min_i32"), + (0x012, "v_max_i32"), + (0x013, "v_min_u32"), + (0x014, "v_max_u32"), + (0x016, "v_lshrrev_b32"), + (0x018, "v_ashrrev_i32"), + (0x01a, "v_lshlrev_b32"), + (0x01b, "v_and_b32"), + (0x01c, "v_or_b32"), + (0x01d, "v_xor_b32"), + (0x01e, "v_xnor_b32"), + (0x01f, "v_mac_f32"), + (0x020, "v_madmk_f32"), + (0x021, "v_madak_f32"), + (0x025, "v_add_nc_u32"), + (0x026, "v_sub_nc_u32"), + (0x027, "v_subrev_nc_u32"), + (0x028, "v_add_co_ci_u32"), + (0x029, "v_sub_co_ci_u32"), + (0x02a, "v_subrev_co_ci_u32"), + (0x02b, "v_fmac_f32"), + (0x02c, "v_fmamk_f32"), + (0x02d, "v_fmaak_f32"), + (0x02f, "v_cvt_pkrtz_f16_f32"), + (0x032, "v_add_f16"), + (0x033, "v_sub_f16"), + (0x034, "v_subrev_f16"), + (0x035, "v_mul_f16"), + (0x036, "v_fmac_f16"), + (0x037, "v_fmamk_f16"), + (0x038, "v_fmaak_f16"), + (0x039, "v_max_f16"), + (0x03a, "v_min_f16"), + (0x03b, "v_ldexp_f16"), + (0x03c, "v_pk_fmac_f16"), +]; + +pub(super) const VOP1: &[(u16, &str)] = &[ + (0x000, "v_nop"), + (0x001, "v_mov_b32"), + (0x002, "v_readfirstlane_b32"), + (0x003, "v_cvt_i32_f64"), + (0x004, "v_cvt_f64_i32"), + (0x005, "v_cvt_f32_i32"), + (0x006, "v_cvt_f32_u32"), + (0x007, "v_cvt_u32_f32"), + (0x008, "v_cvt_i32_f32"), + (0x00a, "v_cvt_f16_f32"), + (0x00b, "v_cvt_f32_f16"), + (0x00c, "v_cvt_rpi_i32_f32"), + (0x00d, "v_cvt_flr_i32_f32"), + (0x00e, "v_cvt_off_f32_i4"), + (0x00f, "v_cvt_f32_f64"), + (0x010, "v_cvt_f64_f32"), + (0x011, "v_cvt_f32_ubyte0"), + (0x012, "v_cvt_f32_ubyte1"), + (0x013, "v_cvt_f32_ubyte2"), + (0x014, "v_cvt_f32_ubyte3"), + (0x015, "v_cvt_u32_f64"), + (0x016, "v_cvt_f64_u32"), + (0x017, "v_trunc_f64"), + (0x018, "v_ceil_f64"), + (0x019, "v_rndne_f64"), + (0x01a, "v_floor_f64"), + (0x01b, "v_pipeflush"), + (0x020, "v_fract_f32"), + (0x021, "v_trunc_f32"), + (0x022, "v_ceil_f32"), + (0x023, "v_rndne_f32"), + (0x024, "v_floor_f32"), + (0x025, "v_exp_f32"), + (0x027, "v_log_f32"), + (0x02a, "v_rcp_f32"), + (0x02b, "v_rcp_iflag_f32"), + (0x02e, "v_rsq_f32"), + (0x02f, "v_rcp_f64"), + (0x031, "v_rsq_f64"), + (0x033, "v_sqrt_f32"), + (0x034, "v_sqrt_f64"), + (0x035, "v_sin_f32"), + (0x036, "v_cos_f32"), + (0x037, "v_not_b32"), + (0x038, "v_bfrev_b32"), + (0x039, "v_ffbh_u32"), + (0x03a, "v_ffbl_b32"), + (0x03b, "v_ffbh_i32"), + (0x03c, "v_frexp_exp_i32_f64"), + (0x03d, "v_frexp_mant_f64"), + (0x03e, "v_fract_f64"), + (0x03f, "v_frexp_exp_i32_f32"), + (0x040, "v_frexp_mant_f32"), + (0x041, "v_clrexcp"), + (0x042, "v_movreld_b32"), + (0x043, "v_movrels_b32"), + (0x044, "v_movrelsd_b32"), + (0x048, "v_movrelsd_2_b32"), + (0x050, "v_cvt_f16_u16"), + (0x051, "v_cvt_f16_i16"), + (0x052, "v_cvt_u16_f16"), + (0x053, "v_cvt_i16_f16"), + (0x054, "v_rcp_f16"), + (0x055, "v_sqrt_f16"), + (0x056, "v_rsq_f16"), + (0x057, "v_log_f16"), + (0x058, "v_exp_f16"), + (0x059, "v_frexp_mant_f16"), + (0x05a, "v_frexp_exp_i16_f16"), + (0x05b, "v_floor_f16"), + (0x05c, "v_ceil_f16"), + (0x05d, "v_trunc_f16"), + (0x05e, "v_rndne_f16"), + (0x05f, "v_fract_f16"), + (0x060, "v_sin_f16"), + (0x061, "v_cos_f16"), + (0x062, "v_sat_pk_u8_i16"), + (0x063, "v_cvt_norm_i16_f16"), + (0x064, "v_cvt_norm_u16_f16"), + (0x065, "v_swap_b32"), + (0x068, "v_swaprel_b32"), +]; + +pub(super) const VOPC: &[(u16, &str)] = &[ + (0x000, "v_cmp_f_f32"), + (0x001, "v_cmp_lt_f32"), + (0x002, "v_cmp_eq_f32"), + (0x003, "v_cmp_le_f32"), + (0x004, "v_cmp_gt_f32"), + (0x005, "v_cmp_lg_f32"), + (0x006, "v_cmp_ge_f32"), + (0x007, "v_cmp_o_f32"), + (0x008, "v_cmp_u_f32"), + (0x009, "v_cmp_nge_f32"), + (0x00a, "v_cmp_nlg_f32"), + (0x00b, "v_cmp_ngt_f32"), + (0x00c, "v_cmp_nle_f32"), + (0x00d, "v_cmp_neq_f32"), + (0x00e, "v_cmp_nlt_f32"), + (0x00f, "v_cmp_tru_f32"), + (0x010, "v_cmpx_f_f32"), + (0x011, "v_cmpx_lt_f32"), + (0x012, "v_cmpx_eq_f32"), + (0x013, "v_cmpx_le_f32"), + (0x014, "v_cmpx_gt_f32"), + (0x015, "v_cmpx_lg_f32"), + (0x016, "v_cmpx_ge_f32"), + (0x017, "v_cmpx_o_f32"), + (0x018, "v_cmpx_u_f32"), + (0x019, "v_cmpx_nge_f32"), + (0x01a, "v_cmpx_nlg_f32"), + (0x01b, "v_cmpx_ngt_f32"), + (0x01c, "v_cmpx_nle_f32"), + (0x01d, "v_cmpx_neq_f32"), + (0x01e, "v_cmpx_nlt_f32"), + (0x01f, "v_cmpx_tru_f32"), + (0x020, "v_cmp_f_f64"), + (0x021, "v_cmp_lt_f64"), + (0x022, "v_cmp_eq_f64"), + (0x023, "v_cmp_le_f64"), + (0x024, "v_cmp_gt_f64"), + (0x025, "v_cmp_lg_f64"), + (0x026, "v_cmp_ge_f64"), + (0x027, "v_cmp_o_f64"), + (0x028, "v_cmp_u_f64"), + (0x029, "v_cmp_nge_f64"), + (0x02a, "v_cmp_nlg_f64"), + (0x02b, "v_cmp_ngt_f64"), + (0x02c, "v_cmp_nle_f64"), + (0x02d, "v_cmp_neq_f64"), + (0x02e, "v_cmp_nlt_f64"), + (0x02f, "v_cmp_tru_f64"), + (0x030, "v_cmpx_f_f64"), + (0x031, "v_cmpx_lt_f64"), + (0x032, "v_cmpx_eq_f64"), + (0x033, "v_cmpx_le_f64"), + (0x034, "v_cmpx_gt_f64"), + (0x035, "v_cmpx_lg_f64"), + (0x036, "v_cmpx_ge_f64"), + (0x037, "v_cmpx_o_f64"), + (0x038, "v_cmpx_u_f64"), + (0x039, "v_cmpx_nge_f64"), + (0x03a, "v_cmpx_nlg_f64"), + (0x03b, "v_cmpx_ngt_f64"), + (0x03c, "v_cmpx_nle_f64"), + (0x03d, "v_cmpx_neq_f64"), + (0x03e, "v_cmpx_nlt_f64"), + (0x03f, "v_cmpx_tru_f64"), + (0x080, "v_cmp_f_i32"), + (0x081, "v_cmp_lt_i32"), + (0x082, "v_cmp_eq_i32"), + (0x083, "v_cmp_le_i32"), + (0x084, "v_cmp_gt_i32"), + (0x085, "v_cmp_ne_i32"), + (0x086, "v_cmp_ge_i32"), + (0x087, "v_cmp_t_i32"), + (0x088, "v_cmp_class_f32"), + (0x089, "v_cmp_lt_i16"), + (0x08a, "v_cmp_eq_i16"), + (0x08b, "v_cmp_le_i16"), + (0x08c, "v_cmp_gt_i16"), + (0x08d, "v_cmp_ne_i16"), + (0x08e, "v_cmp_ge_i16"), + (0x08f, "v_cmp_class_f16"), + (0x090, "v_cmpx_f_i32"), + (0x091, "v_cmpx_lt_i32"), + (0x092, "v_cmpx_eq_i32"), + (0x093, "v_cmpx_le_i32"), + (0x094, "v_cmpx_gt_i32"), + (0x095, "v_cmpx_ne_i32"), + (0x096, "v_cmpx_ge_i32"), + (0x097, "v_cmpx_t_i32"), + (0x098, "v_cmpx_class_f32"), + (0x099, "v_cmpx_lt_i16"), + (0x09a, "v_cmpx_eq_i16"), + (0x09b, "v_cmpx_le_i16"), + (0x09c, "v_cmpx_gt_i16"), + (0x09d, "v_cmpx_ne_i16"), + (0x09e, "v_cmpx_ge_i16"), + (0x09f, "v_cmpx_class_f16"), + (0x0a0, "v_cmp_f_i64"), + (0x0a1, "v_cmp_lt_i64"), + (0x0a2, "v_cmp_eq_i64"), + (0x0a3, "v_cmp_le_i64"), + (0x0a4, "v_cmp_gt_i64"), + (0x0a5, "v_cmp_ne_i64"), + (0x0a6, "v_cmp_ge_i64"), + (0x0a7, "v_cmp_t_i64"), + (0x0a8, "v_cmp_class_f64"), + (0x0a9, "v_cmp_lt_u16"), + (0x0aa, "v_cmp_eq_u16"), + (0x0ab, "v_cmp_le_u16"), + (0x0ac, "v_cmp_gt_u16"), + (0x0ad, "v_cmp_ne_u16"), + (0x0ae, "v_cmp_ge_u16"), + (0x0b0, "v_cmpx_f_i64"), + (0x0b1, "v_cmpx_lt_i64"), + (0x0b2, "v_cmpx_eq_i64"), + (0x0b3, "v_cmpx_le_i64"), + (0x0b4, "v_cmpx_gt_i64"), + (0x0b5, "v_cmpx_ne_i64"), + (0x0b6, "v_cmpx_ge_i64"), + (0x0b7, "v_cmpx_t_i64"), + (0x0b8, "v_cmpx_class_f64"), + (0x0b9, "v_cmpx_lt_u16"), + (0x0ba, "v_cmpx_eq_u16"), + (0x0bb, "v_cmpx_le_u16"), + (0x0bc, "v_cmpx_gt_u16"), + (0x0bd, "v_cmpx_ne_u16"), + (0x0be, "v_cmpx_ge_u16"), + (0x0c0, "v_cmp_f_u32"), + (0x0c1, "v_cmp_lt_u32"), + (0x0c2, "v_cmp_eq_u32"), + (0x0c3, "v_cmp_le_u32"), + (0x0c4, "v_cmp_gt_u32"), + (0x0c5, "v_cmp_ne_u32"), + (0x0c6, "v_cmp_ge_u32"), + (0x0c7, "v_cmp_t_u32"), + (0x0c8, "v_cmp_f_f16"), + (0x0c9, "v_cmp_lt_f16"), + (0x0ca, "v_cmp_eq_f16"), + (0x0cb, "v_cmp_le_f16"), + (0x0cc, "v_cmp_gt_f16"), + (0x0cd, "v_cmp_lg_f16"), + (0x0ce, "v_cmp_ge_f16"), + (0x0cf, "v_cmp_o_f16"), + (0x0d0, "v_cmpx_f_u32"), + (0x0d1, "v_cmpx_lt_u32"), + (0x0d2, "v_cmpx_eq_u32"), + (0x0d3, "v_cmpx_le_u32"), + (0x0d4, "v_cmpx_gt_u32"), + (0x0d5, "v_cmpx_ne_u32"), + (0x0d6, "v_cmpx_ge_u32"), + (0x0d7, "v_cmpx_t_u32"), + (0x0d8, "v_cmpx_f_f16"), + (0x0d9, "v_cmpx_lt_f16"), + (0x0da, "v_cmpx_eq_f16"), + (0x0db, "v_cmpx_le_f16"), + (0x0dc, "v_cmpx_gt_f16"), + (0x0dd, "v_cmpx_lg_f16"), + (0x0de, "v_cmpx_ge_f16"), + (0x0df, "v_cmpx_o_f16"), + (0x0e0, "v_cmp_f_u64"), + (0x0e1, "v_cmp_lt_u64"), + (0x0e2, "v_cmp_eq_u64"), + (0x0e3, "v_cmp_le_u64"), + (0x0e4, "v_cmp_gt_u64"), + (0x0e5, "v_cmp_ne_u64"), + (0x0e6, "v_cmp_ge_u64"), + (0x0e7, "v_cmp_t_u64"), + (0x0e8, "v_cmp_u_f16"), + (0x0e9, "v_cmp_nge_f16"), + (0x0ea, "v_cmp_nlg_f16"), + (0x0eb, "v_cmp_ngt_f16"), + (0x0ec, "v_cmp_nle_f16"), + (0x0ed, "v_cmp_neq_f16"), + (0x0ee, "v_cmp_nlt_f16"), + (0x0ef, "v_cmp_tru_f16"), + (0x0f0, "v_cmpx_f_u64"), + (0x0f1, "v_cmpx_lt_u64"), + (0x0f2, "v_cmpx_eq_u64"), + (0x0f3, "v_cmpx_le_u64"), + (0x0f4, "v_cmpx_gt_u64"), + (0x0f5, "v_cmpx_ne_u64"), + (0x0f6, "v_cmpx_ge_u64"), + (0x0f7, "v_cmpx_t_u64"), + (0x0f8, "v_cmpx_u_f16"), + (0x0f9, "v_cmpx_nge_f16"), + (0x0fa, "v_cmpx_nlg_f16"), + (0x0fb, "v_cmpx_ngt_f16"), + (0x0fc, "v_cmpx_nle_f16"), + (0x0fd, "v_cmpx_neq_f16"), + (0x0fe, "v_cmpx_nlt_f16"), + (0x0ff, "v_cmpx_tru_f16"), +]; + +pub(super) const VOP3: &[(u16, &str)] = &[ + (0x140, "v_mad_legacy_f32"), + (0x141, "v_mad_f32"), + (0x142, "v_mad_i32_i24"), + (0x143, "v_mad_u32_u24"), + (0x144, "v_cubeid_f32"), + (0x145, "v_cubesc_f32"), + (0x146, "v_cubetc_f32"), + (0x147, "v_cubema_f32"), + (0x148, "v_bfe_u32"), + (0x149, "v_bfe_i32"), + (0x14a, "v_bfi_b32"), + (0x14b, "v_fma_f32"), + (0x14c, "v_fma_f64"), + (0x14d, "v_lerp_u8"), + (0x14e, "v_alignbit_b32"), + (0x14f, "v_alignbyte_b32"), + (0x150, "v_mullit_f32"), + (0x151, "v_min3_f32"), + (0x152, "v_min3_i32"), + (0x153, "v_min3_u32"), + (0x154, "v_max3_f32"), + (0x155, "v_max3_i32"), + (0x156, "v_max3_u32"), + (0x157, "v_med3_f32"), + (0x158, "v_med3_i32"), + (0x159, "v_med3_u32"), + (0x15a, "v_sad_u8"), + (0x15b, "v_sad_hi_u8"), + (0x15c, "v_sad_u16"), + (0x15d, "v_sad_u32"), + (0x15e, "v_cvt_pk_u8_f32"), + (0x15f, "v_div_fixup_f32"), + (0x160, "v_div_fixup_f64"), + (0x164, "v_add_f64"), + (0x165, "v_mul_f64"), + (0x166, "v_min_f64"), + (0x167, "v_max_f64"), + (0x168, "v_ldexp_f64"), + (0x169, "v_mul_lo_u32"), + (0x16a, "v_mul_hi_u32"), + (0x16b, "v_mul_lo_i32"), + (0x16c, "v_mul_hi_i32"), + (0x16d, "v_div_scale_f32"), + (0x16e, "v_div_scale_f64"), + (0x16f, "v_div_fmas_f32"), + (0x170, "v_div_fmas_f64"), + (0x171, "v_msad_u8"), + (0x172, "v_qsad_pk_u16_u8"), + (0x173, "v_mqsad_pk_u16_u8"), + (0x174, "v_trig_preop_f64"), + (0x175, "v_mqsad_u32_u8"), + (0x176, "v_mad_u64_u32"), + (0x177, "v_mad_i64_i32"), + (0x178, "v_xor3_b32"), + (0x2ff, "v_lshlrev_b64"), + (0x300, "v_lshrrev_b64"), + (0x301, "v_ashrrev_i64"), + (0x303, "v_add_nc_u16"), + (0x304, "v_sub_nc_u16"), + (0x305, "v_mul_lo_u16"), + (0x307, "v_lshrrev_b16"), + (0x308, "v_ashrrev_i16"), + (0x309, "v_max_u16"), + (0x30a, "v_max_i16"), + (0x30b, "v_min_u16"), + (0x30c, "v_min_i16"), + (0x30d, "v_add_nc_i16"), + (0x30e, "v_sub_nc_i16"), + (0x30f, "v_add_co_u32"), + (0x310, "v_sub_co_u32"), + (0x311, "v_pack_b32_f16"), + (0x312, "v_cvt_pknorm_i16_f16"), + (0x313, "v_cvt_pknorm_u16_f16"), + (0x314, "v_lshlrev_b16"), + (0x319, "v_subrev_co_u32"), + (0x340, "v_mad_u16"), + (0x342, "v_interp_p1ll_f16"), + (0x343, "v_interp_p1lv_f16"), + (0x344, "v_perm_b32"), + (0x345, "v_xad_u32"), + (0x346, "v_lshl_add_u32"), + (0x347, "v_add_lshl_u32"), + (0x34b, "v_fma_f16"), + (0x351, "v_min3_f16"), + (0x352, "v_min3_i16"), + (0x353, "v_min3_u16"), + (0x354, "v_max3_f16"), + (0x355, "v_max3_i16"), + (0x356, "v_max3_u16"), + (0x357, "v_med3_f16"), + (0x358, "v_med3_i16"), + (0x359, "v_med3_u16"), + (0x35a, "v_interp_p2_f16"), + (0x35e, "v_mad_i16"), + (0x35f, "v_div_fixup_f16"), + (0x360, "v_readlane_b32"), + (0x361, "v_writelane_b32"), + (0x362, "v_ldexp_f32"), + (0x363, "v_bfm_b32"), + (0x364, "v_bcnt_u32_b32"), + (0x365, "v_mbcnt_lo_u32_b32"), + (0x366, "v_mbcnt_hi_u32_b32"), + (0x368, "v_cvt_pknorm_i16_f32"), + (0x369, "v_cvt_pknorm_u16_f32"), + (0x36a, "v_cvt_pk_u16_u32"), + (0x36b, "v_cvt_pk_i16_i32"), + (0x36d, "v_add3_u32"), + (0x36f, "v_lshl_or_b32"), + (0x371, "v_and_or_b32"), + (0x372, "v_or3_b32"), + (0x373, "v_mad_u32_u16"), + (0x375, "v_mad_i32_i16"), + (0x376, "v_sub_nc_i32"), + (0x377, "v_permlane16_b32"), + (0x378, "v_permlanex16_b32"), + (0x37f, "v_add_nc_i32"), +]; + +pub(super) const VOP3P: &[(u16, &str)] = &[ + (0x000, "v_pk_mad_i16"), + (0x001, "v_pk_mul_lo_u16"), + (0x002, "v_pk_add_i16"), + (0x003, "v_pk_sub_i16"), + (0x004, "v_pk_lshlrev_b16"), + (0x005, "v_pk_lshrrev_b16"), + (0x006, "v_pk_ashrrev_i16"), + (0x007, "v_pk_max_i16"), + (0x008, "v_pk_min_i16"), + (0x009, "v_pk_mad_u16"), + (0x00a, "v_pk_add_u16"), + (0x00b, "v_pk_sub_u16"), + (0x00c, "v_pk_max_u16"), + (0x00d, "v_pk_min_u16"), + (0x00e, "v_pk_fma_f16"), + (0x00f, "v_pk_add_f16"), + (0x010, "v_pk_mul_f16"), + (0x011, "v_pk_min_f16"), + (0x012, "v_pk_max_f16"), + (0x013, "v_dot2_f32_f16"), + (0x014, "v_dot2_i32_i16"), + (0x015, "v_dot2_u32_u16"), + (0x016, "v_dot4_i32_i8"), + (0x017, "v_dot4_u32_u8"), + (0x019, "v_dot8_u32_u4"), + (0x020, "v_fma_mix_f32"), + (0x021, "v_fma_mixlo_f16"), + (0x022, "v_fma_mixhi_f16"), +]; + +pub(super) const VINTRP: &[(u16, &str)] = &[ + (0x000, "v_interp_p1_f32"), + (0x001, "v_interp_p2_f32"), + (0x002, "v_interp_mov_f32"), +]; + +pub(super) const DS: &[(u16, &str)] = &[ + (0x000, "ds_add_u32"), + (0x001, "ds_sub_u32"), + (0x002, "ds_rsub_u32"), + (0x003, "ds_inc_u32"), + (0x004, "ds_dec_u32"), + (0x005, "ds_min_i32"), + (0x006, "ds_max_i32"), + (0x007, "ds_min_u32"), + (0x008, "ds_max_u32"), + (0x009, "ds_and_b32"), + (0x00a, "ds_or_b32"), + (0x00b, "ds_xor_b32"), + (0x00c, "ds_mskor_b32"), + (0x00d, "ds_write_b32"), + (0x00e, "ds_write2_b32"), + (0x00f, "ds_write2st64_b32"), + (0x010, "ds_cmpst_b32"), + (0x011, "ds_cmpst_f32"), + (0x012, "ds_min_f32"), + (0x013, "ds_max_f32"), + (0x014, "ds_nop"), + (0x015, "ds_add_f32"), + (0x018, "ds_gws_sema_release_all"), + (0x019, "ds_gws_init"), + (0x01a, "ds_gws_sema_v"), + (0x01b, "ds_gws_sema_br"), + (0x01c, "ds_gws_sema_p"), + (0x01d, "ds_gws_barrier"), + (0x01e, "ds_write_b8"), + (0x01f, "ds_write_b16"), + (0x020, "ds_add_rtn_u32"), + (0x021, "ds_sub_rtn_u32"), + (0x022, "ds_rsub_rtn_u32"), + (0x023, "ds_inc_rtn_u32"), + (0x024, "ds_dec_rtn_u32"), + (0x025, "ds_min_rtn_i32"), + (0x026, "ds_max_rtn_i32"), + (0x027, "ds_min_rtn_u32"), + (0x028, "ds_max_rtn_u32"), + (0x029, "ds_and_rtn_b32"), + (0x02a, "ds_or_rtn_b32"), + (0x02b, "ds_xor_rtn_b32"), + (0x02c, "ds_mskor_rtn_b32"), + (0x02d, "ds_wrxchg_rtn_b32"), + (0x02e, "ds_wrxchg2_rtn_b32"), + (0x02f, "ds_wrxchg2st64_rtn_b32"), + (0x030, "ds_cmpst_rtn_b32"), + (0x031, "ds_cmpst_rtn_f32"), + (0x032, "ds_min_rtn_f32"), + (0x033, "ds_max_rtn_f32"), + (0x034, "ds_wrap_rtn_b32"), + (0x035, "ds_swizzle_b32"), + (0x036, "ds_read_b32"), + (0x037, "ds_read2_b32"), + (0x038, "ds_read2st64_b32"), + (0x039, "ds_read_i8"), + (0x03a, "ds_read_u8"), + (0x03b, "ds_read_i16"), + (0x03c, "ds_read_u16"), + (0x03d, "ds_consume"), + (0x03e, "ds_append"), + (0x03f, "ds_ordered_count"), + (0x040, "ds_add_u64"), + (0x041, "ds_sub_u64"), + (0x042, "ds_rsub_u64"), + (0x043, "ds_inc_u64"), + (0x044, "ds_dec_u64"), + (0x045, "ds_min_i64"), + (0x046, "ds_max_i64"), + (0x047, "ds_min_u64"), + (0x048, "ds_max_u64"), + (0x049, "ds_and_b64"), + (0x04a, "ds_or_b64"), + (0x04b, "ds_xor_b64"), + (0x04c, "ds_mskor_b64"), + (0x04d, "ds_write_b64"), + (0x04e, "ds_write2_b64"), + (0x04f, "ds_write2st64_b64"), + (0x050, "ds_cmpst_b64"), + (0x051, "ds_cmpst_f64"), + (0x052, "ds_min_f64"), + (0x053, "ds_max_f64"), + (0x055, "ds_add_rtn_f32"), + (0x060, "ds_add_rtn_u64"), + (0x061, "ds_sub_rtn_u64"), + (0x062, "ds_rsub_rtn_u64"), + (0x063, "ds_inc_rtn_u64"), + (0x064, "ds_dec_rtn_u64"), + (0x065, "ds_min_rtn_i64"), + (0x066, "ds_max_rtn_i64"), + (0x067, "ds_min_rtn_u64"), + (0x068, "ds_max_rtn_u64"), + (0x069, "ds_and_rtn_b64"), + (0x06a, "ds_or_rtn_b64"), + (0x06b, "ds_xor_rtn_b64"), + (0x06c, "ds_mskor_rtn_b64"), + (0x06d, "ds_wrxchg_rtn_b64"), + (0x06e, "ds_wrxchg2_rtn_b64"), + (0x06f, "ds_wrxchg2st64_rtn_b64"), + (0x070, "ds_cmpst_rtn_b64"), + (0x071, "ds_cmpst_rtn_f64"), + (0x072, "ds_min_rtn_f64"), + (0x073, "ds_max_rtn_f64"), + (0x076, "ds_read_b64"), + (0x077, "ds_read2_b64"), + (0x078, "ds_read2st64_b64"), + (0x07e, "ds_condxchg32_rtn_b64"), + (0x080, "ds_add_src2_u32"), + (0x081, "ds_sub_src2_u32"), + (0x082, "ds_rsub_src2_u32"), + (0x083, "ds_inc_src2_u32"), + (0x084, "ds_dec_src2_u32"), + (0x085, "ds_min_src2_i32"), + (0x086, "ds_max_src2_i32"), + (0x087, "ds_min_src2_u32"), + (0x088, "ds_max_src2_u32"), + (0x089, "ds_and_src2_b32"), + (0x08a, "ds_or_src2_b32"), + (0x08b, "ds_xor_src2_b32"), + (0x08d, "ds_write_src2_b32"), + (0x092, "ds_min_src2_f32"), + (0x093, "ds_max_src2_f32"), + (0x095, "ds_add_src2_f32"), + (0x0a0, "ds_write_b8_d16_hi"), + (0x0a1, "ds_write_b16_d16_hi"), + (0x0a2, "ds_read_u8_d16"), + (0x0a3, "ds_read_u8_d16_hi"), + (0x0a4, "ds_read_i8_d16"), + (0x0a5, "ds_read_i8_d16_hi"), + (0x0a6, "ds_read_u16_d16"), + (0x0a7, "ds_read_u16_d16_hi"), + (0x0b0, "ds_write_addtid_b32"), + (0x0b1, "ds_read_addtid_b32"), + (0x0b2, "ds_permute_b32"), + (0x0b3, "ds_bpermute_b32"), + (0x0c0, "ds_add_src2_u64"), + (0x0c1, "ds_sub_src2_u64"), + (0x0c2, "ds_rsub_src2_u64"), + (0x0c3, "ds_inc_src2_u64"), + (0x0c4, "ds_dec_src2_u64"), + (0x0c5, "ds_min_src2_i64"), + (0x0c6, "ds_max_src2_i64"), + (0x0c7, "ds_min_src2_u64"), + (0x0c8, "ds_max_src2_u64"), + (0x0c9, "ds_and_src2_b64"), + (0x0ca, "ds_or_src2_b64"), + (0x0cb, "ds_xor_src2_b64"), + (0x0cd, "ds_write_src2_b64"), + (0x0d2, "ds_min_src2_f64"), + (0x0d3, "ds_max_src2_f64"), + (0x0de, "ds_write_b96"), + (0x0df, "ds_write_b128"), + (0x0fe, "ds_read_b96"), + (0x0ff, "ds_read_b128"), +]; + +pub(super) const MUBUF: &[(u16, &str)] = &[ + (0x000, "buffer_load_format_x"), + (0x001, "buffer_load_format_xy"), + (0x002, "buffer_load_format_xyz"), + (0x003, "buffer_load_format_xyzw"), + (0x004, "buffer_store_format_x"), + (0x005, "buffer_store_format_xy"), + (0x006, "buffer_store_format_xyz"), + (0x007, "buffer_store_format_xyzw"), + (0x008, "buffer_load_ubyte"), + (0x009, "buffer_load_sbyte"), + (0x00a, "buffer_load_ushort"), + (0x00b, "buffer_load_sshort"), + (0x00c, "buffer_load_dword"), + (0x00d, "buffer_load_dwordx2"), + (0x00e, "buffer_load_dwordx4"), + (0x00f, "buffer_load_dwordx3"), + (0x018, "buffer_store_byte"), + (0x019, "buffer_store_byte_d16_hi"), + (0x01a, "buffer_store_short"), + (0x01b, "buffer_store_short_d16_hi"), + (0x01c, "buffer_store_dword"), + (0x01d, "buffer_store_dwordx2"), + (0x01e, "buffer_store_dwordx4"), + (0x01f, "buffer_store_dwordx3"), + (0x020, "buffer_load_ubyte_d16"), + (0x021, "buffer_load_ubyte_d16_hi"), + (0x022, "buffer_load_sbyte_d16"), + (0x023, "buffer_load_sbyte_d16_hi"), + (0x024, "buffer_load_short_d16"), + (0x025, "buffer_load_short_d16_hi"), + (0x026, "buffer_load_format_d16_hi_x"), + (0x027, "buffer_store_format_d16_hi_x"), + (0x030, "buffer_atomic_swap"), + (0x031, "buffer_atomic_cmpswap"), + (0x032, "buffer_atomic_add"), + (0x033, "buffer_atomic_sub"), + (0x034, "buffer_atomic_csub"), + (0x035, "buffer_atomic_smin"), + (0x036, "buffer_atomic_umin"), + (0x037, "buffer_atomic_smax"), + (0x038, "buffer_atomic_umax"), + (0x039, "buffer_atomic_and"), + (0x03a, "buffer_atomic_or"), + (0x03b, "buffer_atomic_xor"), + (0x03c, "buffer_atomic_inc"), + (0x03d, "buffer_atomic_dec"), + (0x03e, "buffer_atomic_fcmpswap"), + (0x03f, "buffer_atomic_fmin"), + (0x040, "buffer_atomic_fmax"), + (0x050, "buffer_atomic_swap_x2"), + (0x051, "buffer_atomic_cmpswap_x2"), + (0x052, "buffer_atomic_add_x2"), + (0x053, "buffer_atomic_sub_x2"), + (0x055, "buffer_atomic_smin_x2"), + (0x056, "buffer_atomic_umin_x2"), + (0x057, "buffer_atomic_smax_x2"), + (0x058, "buffer_atomic_umax_x2"), + (0x059, "buffer_atomic_and_x2"), + (0x05a, "buffer_atomic_or_x2"), + (0x05b, "buffer_atomic_xor_x2"), + (0x05c, "buffer_atomic_inc_x2"), + (0x05d, "buffer_atomic_dec_x2"), + (0x05e, "buffer_atomic_fcmpswap_x2"), + (0x05f, "buffer_atomic_fmin_x2"), + (0x060, "buffer_atomic_fmax_x2"), + (0x071, "buffer_gl0_inv"), + (0x072, "buffer_gl1_inv"), + (0x080, "buffer_load_format_d16_x"), + (0x081, "buffer_load_format_d16_xy"), + (0x082, "buffer_load_format_d16_xyz"), + (0x083, "buffer_load_format_d16_xyzw"), + (0x084, "buffer_store_format_d16_x"), + (0x085, "buffer_store_format_d16_xy"), + (0x086, "buffer_store_format_d16_xyz"), + (0x087, "buffer_store_format_d16_xyzw"), +]; + +pub(super) const MTBUF: &[(u16, &str)] = &[ + (0x000, "tbuffer_load_format_x"), + (0x001, "tbuffer_load_format_xy"), + (0x002, "tbuffer_load_format_xyz"), + (0x003, "tbuffer_load_format_xyzw"), + (0x004, "tbuffer_store_format_x"), + (0x005, "tbuffer_store_format_xy"), + (0x006, "tbuffer_store_format_xyz"), + (0x007, "tbuffer_store_format_xyzw"), + (0x008, "tbuffer_load_format_d16_x"), + (0x009, "tbuffer_load_format_d16_xy"), + (0x00a, "tbuffer_load_format_d16_xyz"), + (0x00b, "tbuffer_load_format_d16_xyzw"), + (0x00c, "tbuffer_store_format_d16_x"), + (0x00d, "tbuffer_store_format_d16_xy"), + (0x00e, "tbuffer_store_format_d16_xyz"), + (0x00f, "tbuffer_store_format_d16_xyzw"), +]; + +pub(super) const MIMG: &[(u16, &str)] = &[ + (0x000, "image_load"), + (0x001, "image_load_mip"), + (0x002, "image_load_pck"), + (0x003, "image_load_pck_sgn"), + (0x004, "image_load_mip_pck"), + (0x005, "image_load_mip_pck_sgn"), + (0x008, "image_store"), + (0x009, "image_store_mip"), + (0x00a, "image_store_pck"), + (0x00b, "image_store_mip_pck"), + (0x00e, "image_get_resinfo"), + (0x00f, "image_atomic_swap"), + (0x010, "image_atomic_cmpswap"), + (0x011, "image_atomic_add"), + (0x012, "image_atomic_sub"), + (0x014, "image_atomic_smin"), + (0x015, "image_atomic_umin"), + (0x016, "image_atomic_smax"), + (0x017, "image_atomic_umax"), + (0x018, "image_atomic_and"), + (0x019, "image_atomic_or"), + (0x01a, "image_atomic_xor"), + (0x01b, "image_atomic_inc"), + (0x01c, "image_atomic_dec"), + (0x01d, "image_atomic_fcmpswap"), + (0x01e, "image_atomic_fmin"), + (0x01f, "image_atomic_fmax"), + (0x020, "image_sample"), + (0x021, "image_sample_cl"), + (0x022, "image_sample_d"), + (0x023, "image_sample_d_cl"), + (0x024, "image_sample_l"), + (0x025, "image_sample_b"), + (0x026, "image_sample_b_cl"), + (0x027, "image_sample_lz"), + (0x028, "image_sample_c"), + (0x029, "image_sample_c_cl"), + (0x02a, "image_sample_c_d"), + (0x02b, "image_sample_c_d_cl"), + (0x02c, "image_sample_c_l"), + (0x02d, "image_sample_c_b"), + (0x02e, "image_sample_c_b_cl"), + (0x02f, "image_sample_c_lz"), + (0x030, "image_sample_o"), + (0x031, "image_sample_cl_o"), + (0x032, "image_sample_d_o"), + (0x033, "image_sample_d_cl_o"), + (0x034, "image_sample_l_o"), + (0x035, "image_sample_b_o"), + (0x036, "image_sample_b_cl_o"), + (0x037, "image_sample_lz_o"), + (0x038, "image_sample_c_o"), + (0x039, "image_sample_c_cl_o"), + (0x03a, "image_sample_c_d_o"), + (0x03b, "image_sample_c_d_cl_o"), + (0x03c, "image_sample_c_l_o"), + (0x03d, "image_sample_c_b_o"), + (0x03e, "image_sample_c_b_cl_o"), + (0x03f, "image_sample_c_lz_o"), + (0x040, "image_gather4"), + (0x041, "image_gather4_cl"), + (0x044, "image_gather4_l"), + (0x045, "image_gather4_b"), + (0x046, "image_gather4_b_cl"), + (0x047, "image_gather4_lz"), + (0x048, "image_gather4_c"), + (0x049, "image_gather4_c_cl"), + (0x04c, "image_gather4_c_l"), + (0x04d, "image_gather4_c_b"), + (0x04e, "image_gather4_c_b_cl"), + (0x04f, "image_gather4_c_lz"), + (0x050, "image_gather4_o"), + (0x051, "image_gather4_cl_o"), + (0x054, "image_gather4_l_o"), + (0x055, "image_gather4_b_o"), + (0x056, "image_gather4_b_cl_o"), + (0x057, "image_gather4_lz_o"), + (0x058, "image_gather4_c_o"), + (0x059, "image_gather4_c_cl_o"), + (0x05c, "image_gather4_c_l_o"), + (0x05d, "image_gather4_c_b_o"), + (0x05e, "image_gather4_c_b_cl_o"), + (0x05f, "image_gather4_c_lz_o"), + (0x060, "image_get_lod"), + (0x068, "image_sample_cd"), + (0x069, "image_sample_cd_cl"), + (0x06a, "image_sample_c_cd"), + (0x06b, "image_sample_c_cd_cl"), + (0x06c, "image_sample_cd_o"), + (0x06d, "image_sample_cd_cl_o"), + (0x06e, "image_sample_c_cd_o"), + (0x06f, "image_sample_c_cd_cl_o"), + (0x080, "image_msaa_load"), + (0x0a2, "image_sample_d_g16"), + (0x0a3, "image_sample_d_cl_g16"), + (0x0aa, "image_sample_c_d_g16"), + (0x0ab, "image_sample_c_d_cl_g16"), + (0x0b2, "image_sample_d_o_g16"), + (0x0b3, "image_sample_d_cl_o_g16"), + (0x0ba, "image_sample_c_d_o_g16"), + (0x0bb, "image_sample_c_d_cl_o_g16"), + (0x0e6, "image_bvh_intersect_ray"), + (0x0e7, "image_bvh64_intersect_ray"), +]; + +pub(super) const FLAT: &[(u16, &str)] = &[ + (0x008, "flat_load_ubyte"), + (0x009, "flat_load_sbyte"), + (0x00a, "flat_load_ushort"), + (0x00b, "flat_load_sshort"), + (0x00c, "flat_load_dword"), + (0x00d, "flat_load_dwordx2"), + (0x00e, "flat_load_dwordx4"), + (0x00f, "flat_load_dwordx3"), + (0x018, "flat_store_byte"), + (0x019, "flat_store_byte_d16_hi"), + (0x01a, "flat_store_short"), + (0x01b, "flat_store_short_d16_hi"), + (0x01c, "flat_store_dword"), + (0x01d, "flat_store_dwordx2"), + (0x01e, "flat_store_dwordx4"), + (0x01f, "flat_store_dwordx3"), + (0x020, "flat_load_ubyte_d16"), + (0x021, "flat_load_ubyte_d16_hi"), + (0x022, "flat_load_sbyte_d16"), + (0x023, "flat_load_sbyte_d16_hi"), + (0x024, "flat_load_short_d16"), + (0x025, "flat_load_short_d16_hi"), + (0x030, "flat_atomic_swap"), + (0x031, "flat_atomic_cmpswap"), + (0x032, "flat_atomic_add"), + (0x033, "flat_atomic_sub"), + (0x035, "flat_atomic_smin"), + (0x036, "flat_atomic_umin"), + (0x037, "flat_atomic_smax"), + (0x038, "flat_atomic_umax"), + (0x039, "flat_atomic_and"), + (0x03a, "flat_atomic_or"), + (0x03b, "flat_atomic_xor"), + (0x03c, "flat_atomic_inc"), + (0x03d, "flat_atomic_dec"), + (0x03e, "flat_atomic_fcmpswap"), + (0x03f, "flat_atomic_fmin"), + (0x040, "flat_atomic_fmax"), + (0x050, "flat_atomic_swap_x2"), + (0x051, "flat_atomic_cmpswap_x2"), + (0x052, "flat_atomic_add_x2"), + (0x053, "flat_atomic_sub_x2"), + (0x055, "flat_atomic_smin_x2"), + (0x056, "flat_atomic_umin_x2"), + (0x057, "flat_atomic_smax_x2"), + (0x058, "flat_atomic_umax_x2"), + (0x059, "flat_atomic_and_x2"), + (0x05a, "flat_atomic_or_x2"), + (0x05b, "flat_atomic_xor_x2"), + (0x05c, "flat_atomic_inc_x2"), + (0x05d, "flat_atomic_dec_x2"), + (0x05e, "flat_atomic_fcmpswap_x2"), + (0x05f, "flat_atomic_fmin_x2"), + (0x060, "flat_atomic_fmax_x2"), +]; + +pub(super) const GLOBAL: &[(u16, &str)] = &[ + (0x008, "global_load_ubyte"), + (0x009, "global_load_sbyte"), + (0x00a, "global_load_ushort"), + (0x00b, "global_load_sshort"), + (0x00c, "global_load_dword"), + (0x00d, "global_load_dwordx2"), + (0x00e, "global_load_dwordx4"), + (0x00f, "global_load_dwordx3"), + (0x016, "global_load_dword_addtid"), + (0x017, "global_store_dword_addtid"), + (0x018, "global_store_byte"), + (0x019, "global_store_byte_d16_hi"), + (0x01a, "global_store_short"), + (0x01b, "global_store_short_d16_hi"), + (0x01c, "global_store_dword"), + (0x01d, "global_store_dwordx2"), + (0x01e, "global_store_dwordx4"), + (0x01f, "global_store_dwordx3"), + (0x020, "global_load_ubyte_d16"), + (0x021, "global_load_ubyte_d16_hi"), + (0x022, "global_load_sbyte_d16"), + (0x023, "global_load_sbyte_d16_hi"), + (0x024, "global_load_short_d16"), + (0x025, "global_load_short_d16_hi"), + (0x030, "global_atomic_swap"), + (0x031, "global_atomic_cmpswap"), + (0x032, "global_atomic_add"), + (0x033, "global_atomic_sub"), + (0x034, "global_atomic_csub"), + (0x035, "global_atomic_smin"), + (0x036, "global_atomic_umin"), + (0x037, "global_atomic_smax"), + (0x038, "global_atomic_umax"), + (0x039, "global_atomic_and"), + (0x03a, "global_atomic_or"), + (0x03b, "global_atomic_xor"), + (0x03c, "global_atomic_inc"), + (0x03d, "global_atomic_dec"), + (0x03e, "global_atomic_fcmpswap"), + (0x03f, "global_atomic_fmin"), + (0x040, "global_atomic_fmax"), + (0x050, "global_atomic_swap_x2"), + (0x051, "global_atomic_cmpswap_x2"), + (0x052, "global_atomic_add_x2"), + (0x053, "global_atomic_sub_x2"), + (0x055, "global_atomic_smin_x2"), + (0x056, "global_atomic_umin_x2"), + (0x057, "global_atomic_smax_x2"), + (0x058, "global_atomic_umax_x2"), + (0x059, "global_atomic_and_x2"), + (0x05a, "global_atomic_or_x2"), + (0x05b, "global_atomic_xor_x2"), + (0x05c, "global_atomic_inc_x2"), + (0x05d, "global_atomic_dec_x2"), + (0x05e, "global_atomic_fcmpswap_x2"), + (0x05f, "global_atomic_fmin_x2"), + (0x060, "global_atomic_fmax_x2"), +]; + +pub(super) const SCRATCH: &[(u16, &str)] = &[ + (0x008, "scratch_load_ubyte"), + (0x009, "scratch_load_sbyte"), + (0x00a, "scratch_load_ushort"), + (0x00b, "scratch_load_sshort"), + (0x00c, "scratch_load_dword"), + (0x00d, "scratch_load_dwordx2"), + (0x00e, "scratch_load_dwordx4"), + (0x00f, "scratch_load_dwordx3"), + (0x018, "scratch_store_byte"), + (0x019, "scratch_store_byte_d16_hi"), + (0x01a, "scratch_store_short"), + (0x01b, "scratch_store_short_d16_hi"), + (0x01c, "scratch_store_dword"), + (0x01d, "scratch_store_dwordx2"), + (0x01e, "scratch_store_dwordx4"), + (0x01f, "scratch_store_dwordx3"), + (0x020, "scratch_load_ubyte_d16"), + (0x021, "scratch_load_ubyte_d16_hi"), + (0x022, "scratch_load_sbyte_d16"), + (0x023, "scratch_load_sbyte_d16_hi"), + (0x024, "scratch_load_short_d16"), + (0x025, "scratch_load_short_d16_hi"), +]; diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs new file mode 100644 index 0000000..214667f --- /dev/null +++ b/crates/victory-shader/src/lib.rs @@ -0,0 +1,26 @@ +//! Xbox Series shaders to host shaders. +//! +//! An Xbox Series shader is a standard DXBC container ([`dxbc`]). Its `DXIL` +//! part ([`dxil`]) may carry Xbox additions around the LLVM bitcode: an +//! `XDAT` table before it indexing blobs after it, among them `xbop` +//! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use +//! console-only intrinsics, so the GFX10 code is translated in general. + +pub mod dxbc; +pub mod dxil; +pub mod gfx10; +pub mod native; + +pub use dxbc::{Container, FourCC, Part}; +pub use dxil::{DxilProgram, ShaderKind, XboxExtras}; +pub use native::{HwStage, NativeProgram, native_programs}; + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum ShaderError { + #[error("not a DXBC container")] + NotDxbc, + #[error("malformed shader: {0}")] + Malformed(&'static str), + #[error("GFX10 code at {offset:#x}: {reason}")] + Isa { offset: usize, reason: &'static str }, +} diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs new file mode 100644 index 0000000..d749f84 --- /dev/null +++ b/crates/victory-shader/src/native.rs @@ -0,0 +1,288 @@ +//! Native GFX10 programs that the console compiler stores in a `DXIL` part. +//! +//! An `XDAT` index after the program header lists blobs stored around the +//! bitcode; one or more of them hold native programs, zlib-packed (a vertex +//! shader can carry two: compiled for use with and without a geometry +//! shader). Layout as observed in shipped titles (index offsets are relative +//! to the part data): +//! +//! ```text +//! +0x18 "XDAT" u32 entry count, u32 (0x24 seen), then per entry: +//! u32 kind, u32 offset, u32 size +//! kind 0x0d "XBCH" u32 version (3), u64 packed size, u64 unpacked size, +//! zlib stream +//! unpacked "FSSM" u32 version (0x101), u64 payload size, payload +//! payload +0x00 u64 graphics slot count (6) +//! +0x08 u64 record offsets: LS HS ES GS VS PS (0x08..0x30), +//! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF +//! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative) +//! ``` +//! +//! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped), +//! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and +//! 0x12 16-byte blobs (0x10 is the shader hash). +//! Unknown versions are rejected so a format change shows up as an error. + +use crate::ShaderError::{self, Malformed}; +use crate::dxbc::{u32_at, u64_at}; + +const XDAT_OFFSET: usize = 0x18; +const MAX_XDAT_ENTRIES: usize = 64; +const KIND_NATIVE: u32 = 0x0d; +const XBCH_VERSION: u32 = 3; +const XBCH_HEADER: usize = 0x18; +const FSSM_VERSION: u32 = 0x101; +const FSSM_HEADER: usize = 0x10; +const GRAPHICS_SLOT_COUNT: u64 = 6; +/// Where each stage's record offset sits in the FSSM payload. +const SLOTS: [(HwStage, usize); 8] = [ + (HwStage::Ls, 0x08), + (HwStage::Hs, 0x10), + (HwStage::Es, 0x18), + (HwStage::Gs, 0x20), + (HwStage::Vs, 0x28), + (HwStage::Ps, 0x30), + (HwStage::Ms, 0x48), + (HwStage::Cs, 0x60), +]; +const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF; +/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes. +const MAX_UNPACKED: u64 = 16 << 20; + +/// Hardware shader stage a native program runs as. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum HwStage { + Ls, + Hs, + Es, + Gs, + Vs, + Ps, + /// Mesh shader. + Ms, + Cs, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeProgram { + pub stage: HwStage, + /// GFX10 machine code. + pub code: Vec, +} + +/// The native programs in a `DXIL` part's data; empty for the PC layout. +pub fn native_programs(part: &[u8]) -> Result, ShaderError> { + if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") { + return Ok(Vec::new()); + } + let count = u32_at(part, XDAT_OFFSET + 4)? as usize; + if count > MAX_XDAT_ENTRIES { + return Err(Malformed("implausible XDAT entry count")); + } + let mut out = Vec::new(); + for i in 0..count { + let at = XDAT_OFFSET + 12 + 12 * i; + if u32_at(part, at)? != KIND_NATIVE { + continue; + } + let offset = u32_at(part, at + 4)?.into(); + let size = u32_at(part, at + 8)?.into(); + let blob = bytes(part, offset, size).ok_or(Malformed("XDAT entry out of bounds"))?; + out.extend(programs(&unpack(blob)?)?); + } + Ok(out) +} + +fn unpack(blob: &[u8]) -> Result, ShaderError> { + if blob.get(0..4) != Some(b"XBCH") { + return Err(Malformed("native blob lacks XBCH magic")); + } + if u32_at(blob, 4)? != XBCH_VERSION { + return Err(Malformed("unknown XBCH version")); + } + let packed = u64_at(blob, 8)?; + let unpacked = u64_at(blob, 16)?; + if unpacked > MAX_UNPACKED { + return Err(Malformed("implausible XBCH unpacked size")); + } + let stream = + bytes(blob, XBCH_HEADER as u64, packed).ok_or(Malformed("XBCH stream out of bounds"))?; + let out = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(stream, unpacked as usize) + .map_err(|_| Malformed("XBCH stream does not inflate to its stated size"))?; + if out.len() as u64 != unpacked { + return Err(Malformed("XBCH stream does not inflate to its stated size")); + } + Ok(out) +} + +fn programs(fssm: &[u8]) -> Result, ShaderError> { + if fssm.get(0..4) != Some(b"FSSM") { + return Err(Malformed("native blob lacks FSSM magic")); + } + if u32_at(fssm, 4)? != FSSM_VERSION { + return Err(Malformed("unknown FSSM version")); + } + let payload = &fssm[FSSM_HEADER.min(fssm.len())..]; + if u64_at(fssm, 8)? != payload.len() as u64 { + return Err(Malformed("FSSM payload size disagrees")); + } + if u64_at(payload, 0)? != GRAPHICS_SLOT_COUNT { + return Err(Malformed("unexpected FSSM slot count")); + } + let mut out = Vec::new(); + for (stage, at) in SLOTS { + let record = u64_at(payload, at)?; + if record == ABSENT { + continue; + } + let record = bytes(payload, record, 16).ok_or(Malformed("FSSM record out of bounds"))?; + let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?) + .ok_or(Malformed("native code out of bounds"))?; + out.push(NativeProgram { + stage, + code: code.to_vec(), + }); + } + Ok(out) +} + +/// `data[offset..offset + len]` with untrusted 64-bit bounds. +fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> { + let start = usize::try_from(offset).ok()?; + data.get(start..start.checked_add(usize::try_from(len).ok()?)?) +} + +#[cfg(test)] +mod tests { + use super::*; + + const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8]; + const PS_CODE: [u8; 4] = [9, 10, 11, 12]; + + fn slot(stage: HwStage) -> usize { + SLOTS.iter().find(|s| s.0 == stage).unwrap().1 + } + + /// FSSM blob with `programs` as (stage, code) pairs. + fn fssm(programs: &[(HwStage, &[u8])]) -> Vec { + let mut payload = GRAPHICS_SLOT_COUNT.to_le_bytes().to_vec(); + payload.resize(slot(HwStage::Cs) + 8, 0); + for (_, at) in SLOTS { + payload[at..at + 8].copy_from_slice(&ABSENT.to_le_bytes()); + } + for &(stage, code) in programs { + let slot = slot(stage); + let record = payload.len() as u64; + payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes()); + payload.extend_from_slice(&(record + 16).to_le_bytes()); + payload.extend_from_slice(&(code.len() as u64).to_le_bytes()); + payload.extend_from_slice(code); + } + let mut out = b"FSSM".to_vec(); + out.extend_from_slice(&FSSM_VERSION.to_le_bytes()); + out.extend_from_slice(&(payload.len() as u64).to_le_bytes()); + out.extend_from_slice(&payload); + out + } + + fn xbch(unpacked: &[u8]) -> Vec { + let stream = miniz_oxide::deflate::compress_to_vec_zlib(unpacked, 6); + let mut out = b"XBCH".to_vec(); + out.extend_from_slice(&XBCH_VERSION.to_le_bytes()); + out.extend_from_slice(&(stream.len() as u64).to_le_bytes()); + out.extend_from_slice(&(unpacked.len() as u64).to_le_bytes()); + out.extend_from_slice(&stream); + out + } + + /// `DXIL` part data: program header, XDAT index, then the blobs. + fn part(blobs: &[(u32, &[u8])]) -> Vec { + let mut out = vec![0u8; XDAT_OFFSET]; + out.extend_from_slice(b"XDAT"); + out.extend_from_slice(&(blobs.len() as u32).to_le_bytes()); + out.extend_from_slice(&0x24u32.to_le_bytes()); + let mut offset = out.len() + 12 * blobs.len(); + for (kind, blob) in blobs { + for v in [*kind, offset as u32, blob.len() as u32] { + out.extend_from_slice(&v.to_le_bytes()); + } + offset += blob.len(); + } + for (_, blob) in blobs { + out.extend_from_slice(blob); + } + out + } + + #[test] + fn finds_graphics_programs() { + let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)])); + let data = part(&[(0x0a, b"xbop"), (KIND_NATIVE, &native)]); + let found = native_programs(&data).unwrap(); + assert_eq!( + found, + [ + NativeProgram { + stage: HwStage::Vs, + code: VS_CODE.to_vec() + }, + NativeProgram { + stage: HwStage::Ps, + code: PS_CODE.to_vec() + }, + ] + ); + } + + #[test] + fn finds_mesh_and_compute_programs() { + for stage in [HwStage::Ms, HwStage::Cs] { + let data = part(&[(KIND_NATIVE, &xbch(&fssm(&[(stage, &VS_CODE)])))]); + let found = native_programs(&data).unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].stage, stage); + } + } + + #[test] + fn reads_every_native_blob() { + let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)])); + let vs = xbch(&fssm(&[(HwStage::Vs, &VS_CODE)])); + let data = part(&[(0x12, &[0; 16]), (KIND_NATIVE, &es), (KIND_NATIVE, &vs)]); + let stages: Vec<_> = native_programs(&data) + .unwrap() + .iter() + .map(|p| p.stage) + .collect(); + assert_eq!(stages, [HwStage::Es, HwStage::Vs]); + } + + #[test] + fn pc_layout_has_none() { + assert!(native_programs(&[0u8; 64]).unwrap().is_empty()); + assert!( + native_programs(&part(&[(0x0a, b"xbop")])) + .unwrap() + .is_empty() + ); + } + + #[test] + fn rejects_corrupt_blobs() { + let good = xbch(&fssm(&[(HwStage::Ls, &VS_CODE)])); + let corrupt = |at: usize, byte: u8| { + let mut blob = good.clone(); + blob[at] = byte; + native_programs(&part(&[(KIND_NATIVE, &blob)])) + }; + assert!(corrupt(4, 9).is_err(), "unknown version"); + assert!(corrupt(16, 0xFF).is_err(), "stated size"); + assert!(corrupt(XBCH_HEADER + 2, 0xFF).is_err(), "zlib stream"); + assert!(native_programs(&part(&[(KIND_NATIVE, &good[..20])])).is_err()); + + let mut bad_record = fssm(&[(HwStage::Ls, &VS_CODE)]); + let at = FSSM_HEADER + slot(HwStage::Ls); + bad_record[at..at + 8].copy_from_slice(&u64::MAX.to_le_bytes()); + assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err()); + } +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..2cca2eb --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,57 @@ +# Architecture + +``` + user's files (outside repo) VIctory + ─────────────────────────── ───────────────────────────────────────── + game assets ──────────────────────────► victory-pipeline + victory-game + (victory-formats, victory-shader) + │ + ▼ + cache_dir: converted data + │ + game executable ─► victory-loader ────► title code (native x86-64) + prepare, map, bind │ imports + ▼ + victory-hle ── host Windows (shared APIs) + │ D3D12.X + ▼ + victory-gpu ─► host D3D12 + │ shaders at pipeline creation + ▼ + victory-shader ◄─► cache_dir +``` + +Shaders are translated when the title creates a pipeline, from the bytes it +passes, wherever it loaded them from (executable, archive, memory). +Converting them ahead of time from files is only a warm-up. + +## Crates + +| Crate | Role | +|-------|------| +| `victory-core` | config, asset-policy guard, logging | +| `victory-pe` | read-only PE32+ and import-library analysis | +| `victory-loader` | prepare, map, bind and start the title image | +| `victory-hle` | console API implementations, host pass-through policy | +| `victory-gpu` | D3D12.X packet streams and GPU memory → host D3D12 (skeleton) | +| `victory-shader` | Xbox shader containers → host shaders | +| `victory-formats` | texture layouts, BCPack, audio codecs (skeleton) | +| `victory-pipeline` | converter trait, content-addressed cache | +| `victory-game` | Grand Theft Auto VI-specific formats, build identities, hooks | +| `apps/victory` | command-line front end | +| `xtask` | asset-policy check, git hooks | +| `tests/fixtures/hle-probe` | a stand-in "title" (our own code) for loader tests | + +Everything except `victory-game` is platform-level and can be tested with +any Xbox Series title. + +## Import resolution + +For every `dll!function` the title imports, in order: + +1. our implementation in `victory-hle::modules` (always wins); +2. the host's own function, if `HostPolicy` allows that DLL; +3. a generated stub that names the import when called (`--unimplemented + trap` breaks into the debugger and aborts; `zero` logs once and returns 0). + +`victory census` shows this classification without running anything. diff --git a/docs/asset-policy.md b/docs/asset-policy.md new file mode 100644 index 0000000..b4f9fe0 --- /dev/null +++ b/docs/asset-policy.md @@ -0,0 +1,49 @@ +# Asset policy (rule #1) + +**Nothing from the game is ever stored in this repository.** Everything is +built on the user's machine from files the user supplies. The same applies +to other titles used for testing, and to any other proprietary material. + +## Not allowed + +In any form (files, string literals, fixtures, snapshots, docs): + +* assets: models, textures, shaders, audio, video, text, archives; +* the executable or any part of it: data sections, strings, tables, + resources, code beyond the signatures below; +* anything derived from those: converted assets, decompiled or + disassembled code, shader dumps, extracted tables, screenshots. + +## Allowed + +* our own code that understands formats; +* build identities: BLAKE3 of an executable, CodeView GUID/age; +* per-build offsets of functions we hook, under names we choose; +* byte-pattern signatures that locate functions or data in the executable; +* small interoperability constants (magic numbers, enum values) we write; +* synthetic test data generated by our own code. + +## Where data lives + +Outside the repository, configured in `victory.toml`: `game_dir` (the +user's dump), `test_titles`, and `cache_dir` for everything derived +(default `%LOCALAPPDATA%\victory\cache`). + +## Enforcement + +1. `.gitignore` keeps common data types out of `git status`. +2. `cargo xtask policy` (run by the pre-commit hook; install with + `cargo xtask install-hooks`) is an allowlist: files must have an allowed + type, be under 512 KiB, contain no binary data or known binary + signatures, and hold no long hex/base64 runs. Exceptions need an entry + with a reason in `xtask/src/policy.rs`. +3. At runtime, everything that writes derived data calls + `victory_core::ensure_outside_repo`. +4. Tests that need real files take their paths from environment variables + and skip when unset. They assert on properties, never on snapshots. + +## If something slips through + +A follow-up commit is not enough. Rewrite history +(`git filter-repo --path --invert-paths`), force-push, and have +everyone re-clone. diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..080921b --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,5 @@ +[toolchain] +channel = "1.98.1" +targets = ["x86_64-pc-windows-msvc"] +components = ["rustfmt", "clippy"] +profile = "minimal" diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..8d1691c --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 100 +use_field_init_shorthand = true diff --git a/tests/fixtures/hle-probe/Cargo.lock b/tests/fixtures/hle-probe/Cargo.lock new file mode 100644 index 0000000..354c81d --- /dev/null +++ b/tests/fixtures/hle-probe/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "hle-probe" +version = "0.0.0" diff --git a/tests/fixtures/hle-probe/Cargo.toml b/tests/fixtures/hle-probe/Cargo.toml new file mode 100644 index 0000000..6c7f87b --- /dev/null +++ b/tests/fixtures/hle-probe/Cargo.toml @@ -0,0 +1,18 @@ +# A tiny stand-in for an Xbox title, used by victory-loader's integration +# tests. It is NOT a workspace member: the tests build it on demand into its +# own target directory. It imports from DLLs that do not exist on a PC +# (via raw-dylib), so it can only work when loaded through victory-loader. +[package] +name = "hle-probe" +version = "0.0.0" +edition = "2024" +license = "GPL-3.0-or-later" +publish = false + +[lib] +crate-type = ["cdylib"] + +[profile.dev] +panic = "abort" + +[workspace] diff --git a/tests/fixtures/hle-probe/build.rs b/tests/fixtures/hle-probe/build.rs new file mode 100644 index 0000000..45ab457 --- /dev/null +++ b/tests/fixtures/hle-probe/build.rs @@ -0,0 +1,4 @@ +fn main() { + println!("cargo:rustc-link-arg-cdylib=/DELAYLOAD:victory-probe-delayed.dll"); + println!("cargo:rustc-link-lib=delayimp"); +} diff --git a/tests/fixtures/hle-probe/src/lib.rs b/tests/fixtures/hle-probe/src/lib.rs new file mode 100644 index 0000000..8ee844e --- /dev/null +++ b/tests/fixtures/hle-probe/src/lib.rs @@ -0,0 +1,55 @@ +//! A stand-in for a title, written by us. It imports from DLLs that do not +//! exist on a PC, which is exactly the situation victory-loader handles. +//! Loaded normally, this DLL would fail with "module not found". + +#[link(name = "xgameruntime", kind = "raw-dylib")] +unsafe extern "system" { + fn XGameRuntimeInitialize() -> i32; +} + +#[link(name = "victory-probe-missing", kind = "raw-dylib")] +unsafe extern "system" { + fn VIctoryProbeNotImplemented(x: u64) -> u64; +} + +// Delay-loaded (see build.rs): bound through the delay-load table. +#[link(name = "victory-probe-delayed", kind = "raw-dylib")] +unsafe extern "system" { + fn VIctoryProbeDelayed() -> u32; +} + +#[link(name = "kernel32")] +unsafe extern "system" { + fn GetTickCount() -> u32; + fn GetCurrentProcessId() -> u32; +} + +/// Console-only API, answered by the resolver's HLE implementation. +#[unsafe(no_mangle)] +pub extern "system" fn probe_xgameruntime_init() -> i32 { + unsafe { XGameRuntimeInitialize() } +} + +/// Exists on the host too, but the resolver overrides it. +#[unsafe(no_mangle)] +pub extern "system" fn probe_tick() -> u32 { + unsafe { GetTickCount() } +} + +/// Exists on the host and is passed through to it. +#[unsafe(no_mangle)] +pub extern "system" fn probe_pid() -> u32 { + unsafe { GetCurrentProcessId() } +} + +/// A delay-loaded console API. +#[unsafe(no_mangle)] +pub extern "system" fn probe_delayed() -> u32 { + unsafe { VIctoryProbeDelayed() } +} + +/// Nobody implements this one: it must land in an unimplemented-import stub. +#[unsafe(no_mangle)] +pub extern "system" fn probe_missing() -> u64 { + unsafe { VIctoryProbeNotImplemented(42) } +} diff --git a/victory.example.toml b/victory.example.toml new file mode 100644 index 0000000..ee48e75 --- /dev/null +++ b/victory.example.toml @@ -0,0 +1,15 @@ +# Copy to `victory.toml` (git-ignored) and point it at YOUR files. +# Every path must be OUTSIDE the repository; the tools refuse otherwise. +# Environment variables (shown below) take precedence over this file. +# VICTORY_CONFIG selects a different config file. + +[paths] +# Your own dump of Grand Theft Auto VI. env: VICTORY_GAME_DIR +game_dir = 'D:\victory-data\game' + +# Derived data. Default: %LOCALAPPDATA%\victory\cache. env: VICTORY_CACHE_DIR +# cache_dir = 'D:\victory-data\cache' + +# Other Xbox Series titles used to test platform-level code. +# env: VICTORY_TEST_TITLES (separated by ';') +test_titles = [] diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 0000000..d8e74bf --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "xtask" +description = "Repository maintenance: asset-policy enforcement and git hooks." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +anyhow.workspace = true +clap.workspace = true +walkdir.workspace = true + +[lints] +workspace = true diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 0000000..911ed80 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,56 @@ +//! Repository maintenance. Run with `cargo xtask `. + +mod policy; + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use anyhow::{Context, Result}; +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[command(name = "xtask")] +struct Cli { + #[command(subcommand)] + command: Cmd, +} + +#[derive(Subcommand)] +enum Cmd { + /// Enforce the asset policy: the repository holds only small text files + /// we wrote. Checks tracked and untracked-but-not-ignored files. + Policy { + /// Check only what is staged for commit (used by the pre-commit hook). + #[arg(long)] + staged: bool, + }, + /// Point git at .githooks/ so every commit runs the policy check. + InstallHooks, +} + +fn main() -> Result<()> { + let root = workspace_root(); + match Cli::parse().command { + Cmd::Policy { staged } => policy::run(&root, staged), + Cmd::InstallHooks => { + let status = Command::new("git") + .args(["config", "core.hooksPath", ".githooks"]) + .current_dir(&root) + .status() + .context("running git")?; + anyhow::ensure!( + status.success(), + "git config failed (is this a git repository?)" + ); + println!("hooks installed: commits now run `cargo xtask policy --staged`"); + Ok(()) + } + } +} + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("xtask lives in the workspace") + .into() +} diff --git a/xtask/src/policy.rs b/xtask/src/policy.rs new file mode 100644 index 0000000..e0960dc --- /dev/null +++ b/xtask/src/policy.rs @@ -0,0 +1,220 @@ +//! Rule #1, statically: the repository only ever contains small text files +//! that we wrote. See docs/asset-policy.md. +//! +//! This is an allowlist, not a blocklist: a file passes only if its name is +//! on the list, it is not too big, it is text, and it does not smuggle data +//! inside text (long hex/base64 runs). + +use std::path::Path; +use std::process::Command; + +use anyhow::{Context, Result, bail}; + +const MAX_FILE_SIZE: usize = 512 * 1024; +const MAX_ENCODED_RUN: usize = 512; + +const ALLOWED_EXTENSIONS: &[&str] = &[ + "rs", "toml", "md", "txt", "lock", "yml", "yaml", "json", "hlsl", "hlsli", "ps1", "cmd", "sh", +]; +const ALLOWED_NAMES: &[&str] = &[ + ".gitignore", + ".gitattributes", + ".editorconfig", + ".victory-root", + "pre-commit", + "LICENSE", + "LICENSE-MIT", + "LICENSE-APACHE", +]; + +/// Paths explicitly exempted, with a reason. Keep this empty if at all possible. +const EXCEPTIONS: &[(&str, &str)] = &[]; + +/// Signatures of formats that must never be committed. +const FORBIDDEN_MAGIC: &[(&[u8], &str)] = &[ + (b"MZ", "PE executable"), + (b"DXBC", "shader container"), + (b"DDS ", "DDS texture"), + (b"RIFF", "RIFF (audio/video)"), + (b"BC\xC0\xDE", "LLVM bitcode"), + (b"Microsoft C/C++ MSF", "PDB"), + (b"!", "library archive"), + (b"PK\x03\x04", "zip"), + (b"7z\xBC\xAF", "7-zip"), + (b"MSCF", "cabinet"), + (b"\xD0\xCF\x11\xE0", "MSI/OLE"), +]; + +pub fn run(root: &Path, staged: bool) -> Result<()> { + let files = list_files(root, staged)?; + let mut violations = Vec::new(); + for path in &files { + if EXCEPTIONS.iter().any(|(p, _)| p == path) { + continue; + } + let content = if staged { + let out = Command::new("git") + .args(["show", &format!(":{path}")]) + .current_dir(root) + .output()?; + if !out.status.success() { + continue; // deleted in the index + } + out.stdout + } else { + match std::fs::read(root.join(path)) { + Ok(c) => c, + Err(_) => continue, + } + }; + for problem in check(path, &content) { + violations.push(format!("{path}: {problem}")); + } + } + if violations.is_empty() { + println!("asset policy: {} files ok", files.len()); + return Ok(()); + } + for v in &violations { + eprintln!("POLICY: {v}"); + } + bail!( + "{} asset-policy violation(s). Nothing from the game may be committed; \ + see docs/asset-policy.md", + violations.len() + ) +} + +fn list_files(root: &Path, staged: bool) -> Result> { + let git = |args: &[&str]| -> Result>> { + let out = Command::new("git") + .args(args) + .current_dir(root) + .output() + .context("running git")?; + if !out.status.success() { + return Ok(None); + } + Ok(Some( + out.stdout + .split(|&b| b == 0) + .filter(|s| !s.is_empty()) + .map(|s| String::from_utf8_lossy(s).replace('\\', "/")) + .collect(), + )) + }; + if staged { + return git(&[ + "diff", + "--cached", + "--name-only", + "--diff-filter=ACMR", + "-z", + ])? + .context("--staged needs a git repository"); + } + if let Some(mut tracked) = git(&[ + "ls-files", + "-z", + "--cached", + "--others", + "--exclude-standard", + ])? { + tracked.sort(); + tracked.dedup(); + return Ok(tracked); + } + // Not a git repository: walk everything except build output. + Ok(walkdir::WalkDir::new(root) + .into_iter() + .filter_entry(|e| !matches!(e.file_name().to_str(), Some("target" | ".git"))) + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file()) + .filter_map(|e| { + e.path() + .strip_prefix(root) + .ok() + .map(|p| p.to_string_lossy().replace('\\', "/")) + }) + .collect()) +} + +/// All problems with one file. Pure, for testing. +pub fn check(path: &str, content: &[u8]) -> Vec { + let mut problems = Vec::new(); + let name = path.rsplit('/').next().unwrap_or(path); + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()); + let allowed = ALLOWED_NAMES.contains(&name) + || ext + .as_deref() + .is_some_and(|e| ALLOWED_EXTENSIONS.contains(&e)); + if !allowed { + problems.push("file type not on the allowlist".to_owned()); + } + if content.len() > MAX_FILE_SIZE { + problems.push(format!( + "{} bytes exceeds the {MAX_FILE_SIZE}-byte limit", + content.len() + )); + } + for (magic, what) in FORBIDDEN_MAGIC { + if content.starts_with(magic) { + problems.push(format!("looks like a {what}")); + } + } + if content.contains(&0) { + problems.push("binary content (NUL bytes)".to_owned()); + } else if let Some(run) = longest_encoded_run(content) + && run > MAX_ENCODED_RUN + { + problems.push(format!("{run}-character hex/base64 run (embedded data?)")); + } + problems +} + +/// Longest run of characters that could be hex or base64 payload. +fn longest_encoded_run(content: &[u8]) -> Option { + let is_payload = |b: &u8| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'='); + content.split(|b| !is_payload(b)).map(<[u8]>::len).max() +} + +#[cfg(test)] +mod tests { + use super::check; + + /// Enforces the policy wherever tests run, even in clones without the hook. + #[test] + fn repository_passes_policy() { + super::run(&crate::workspace_root(), false).unwrap(); + } + + #[test] + fn accepts_source() { + assert!(check("crates/x/src/lib.rs", b"fn main() {}\n").is_empty()); + assert!(check(".gitignore", b"/target/\n").is_empty()); + assert!(check(".githooks/pre-commit", b"#!/bin/sh\n").is_empty()); + } + + #[test] + fn rejects_game_like_files() { + assert!(!check("assets/tex.dds", b"DDS \x7c\0\0\0").is_empty()); + assert!( + !check("notes.txt", b"MZ\x90\0").is_empty(), + "magic wins over extension" + ); + assert!( + !check("data.bin", b"hello").is_empty(), + "extension not allowed" + ); + assert!( + !check("a.rs", &vec![b'a'; 600 * 1024]).is_empty(), + "too big" + ); + } + + #[test] + fn rejects_data_smuggled_into_text() { + let blob = format!("const DATA: &str = \"{}\";", "A1".repeat(400)); + assert!(!check("src/blob.rs", blob.as_bytes()).is_empty()); + } +}