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 <[email protected]>
This commit is contained in:
MarvisandClaude Sonnet 5.5 committed 2026-11-23 01:15:26 +01:00
commit f4504f6413
69 files changed
+7952

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
[alias]
xtask = "run --quiet --package xtask --"
+4
View File
@@ -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
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
# Enforces the asset policy on every commit. Install with: cargo xtask install-hooks
exec cargo xtask policy --staged
+76
View File
@@ -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
+5
View File
@@ -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.
Generated
+780
View File
@@ -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",
]
+56
View File
@@ -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"
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+43
View File
@@ -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 <exe|dll> [--imports] [--exports]
victory census [paths...] [--missing] [--strict]
victory lib-exports <import.lib> [--list]
victory shader-info [paths...] [--verbose] [--disasm]
victory run <exe> [--execute] [--unimplemented trap|zero] [--strict]
victory config
```
Logging: `VICTORY_LOG=victory_loader=trace,info`.
## License
GPL-3.0-or-later. See [LICENSE](LICENSE).
+24
View File
@@ -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
+123
View File
@@ -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<ImportSymbol>,
hle: usize,
host: usize,
missing: usize,
images: BTreeSet<PathBuf>,
}
pub fn run(paths: Vec<PathBuf>, 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<String, DllStats> = BTreeMap::new();
let mut missing: BTreeMap<(String, String), BTreeSet<PathBuf>> = 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"
}
+153
View File
@@ -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<String, Vec<String>> = 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(", "))
}
}
+165
View File
@@ -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<PathBuf>,
/// 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<PathBuf>,
/// 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<PathBuf>| 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<PathBuf>) -> Result<Vec<PathBuf>> {
if !paths.is_empty() {
return Ok(paths);
}
let cfg = victory_core::Config::load()?;
let all: Vec<PathBuf> = 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)
}
+64
View File
@@ -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")
}
+176
View File
@@ -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<String, usize>,
with_native: usize,
native_stages: BTreeMap<HwStage, usize>,
native_errors: BTreeMap<String, usize>,
decoded: usize,
instructions: usize,
unnamed: BTreeMap<String, usize>,
decode_errors: BTreeMap<&'static str, usize>,
files_with_shaders: usize,
}
pub fn run(paths: Vec<PathBuf>, 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(" "))
}
+21
View File
@@ -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
+166
View File
@@ -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<PathBuf>,
/// 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<PathBuf>,
/// The config file that was read, if any.
pub source: Option<PathBuf>,
}
#[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<PathBuf>,
cache_dir: Option<PathBuf>,
#[serde(default)]
test_titles: Vec<PathBuf>,
}
impl Config {
/// Loads configuration from the environment and the config file.
pub fn load() -> Result<Self> {
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<PathBuf>,
env: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Result<Self> {
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 `<cache>/<sub>`, creating it, after checking the asset policy.
pub fn cache_subdir(&self, sub: &str) -> Result<PathBuf> {
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<PathBuf> {
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());
}
}
+13
View File
@@ -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};
+19
View File
@@ -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();
}
+159
View File
@@ -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<PathBuf, PolicyError> {
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();
}
}
+11
View File
@@ -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
+6
View File
@@ -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.
+11
View File
@@ -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
+23
View File
@@ -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))
}
+11
View File
@@ -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
+12
View File
@@ -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).
+25
View File
@@ -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
+123
View File
@@ -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<String>,
}
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<usize> {
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<Mutex<HashMap<String, usize>>> = LazyLock::new(Default::default);
pub(super) fn resolve(dll: &str, symbol: &ImportSymbol) -> Option<usize> {
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<usize> {
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<usize> {
None
}
}
+120
View File
@@ -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<Provenance> {
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)
);
}
}
+65
View File
@@ -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()
}
}
+19
View File
@@ -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<HleModule> {
vec![kernel::module(), xgameruntime::module()]
}
@@ -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),
],
}
}
+94
View File
@@ -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<HleExport>,
}
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<Vec<HleModule>> = LazyLock::new(modules::all);
/// All modules we implement.
pub fn registry() -> &'static [HleModule] {
&REGISTRY
}
pub(crate) fn lookup(dll: &str, name: &str) -> Option<usize> {
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"));
}
}
+18
View File
@@ -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<usize> {
match MAIN_IMAGE_BASE.load(Ordering::Acquire) {
0 => None,
base => Some(base),
}
}
@@ -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");
}
+31
View File
@@ -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
+35
View File
@@ -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;
+141
View File
@@ -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<u8>,
/// 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<PreparedImage, PrepareError> {
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());
}
}
+31
View File
@@ -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;
}
+149
View File
@@ -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, <unimplemented_import> ; 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<Self> {
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<usize> {
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(())
}
}
+250
View File
@@ -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<MissingImport>,
}
/// 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<LoadedImage> {
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<u16> = 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<usize> {
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<BindReport> {
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<Self>) -> Result<std::thread::JoinHandle<u32>> {
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) };
}
}
+155
View File
@@ -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<usize> {
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();
}
}
+15
View File
@@ -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
+472
View File
@@ -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<SectionInfo>,
pub imports: Vec<ImportModule>,
pub delay_imports: Vec<ImportModule>,
pub exports: Vec<ExportInfo>,
pub tls: Option<TlsInfo>,
pub has_relocations: bool,
pub has_exception_table: bool,
pub has_load_config: bool,
pub codeview: Option<CodeViewInfo>,
}
#[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<ImportEntry>,
}
#[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<String>,
pub ordinal: u16,
/// `None` for forwarded exports.
pub rva: Option<u32>,
/// `"dll.name"` or `"dll.#ordinal"` for forwarded exports.
pub forward: Option<String>,
}
#[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<u32>,
}
/// 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<Self, PeError> {
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<u32> {
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<Vec<ImportModule>, 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::<ImageNtHeaders64>(t)
})?,
});
}
Ok(modules)
}
fn parse_delay_imports(
file: &PeFile64<'_>,
size_of_image: u32,
) -> Result<Vec<ImportModule>, 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::<ImageNtHeaders64>(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<Import<'data>>,
) -> Result<Vec<ImportEntry>, PeError> {
let mut entries = Vec::new();
while let Some(thunk) = thunks.next::<ImageNtHeaders64>()? {
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<Vec<ExportInfo>, 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<Option<TlsInfo>, 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<u32, PeError> {
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<u8> {
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);
}
}
+66
View File
@@ -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<LibImport>,
/// 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<Self, PeError> {
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)
}
}
+91
View File
@@ -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<usize> {
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<usize> {
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<usize> {
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<u32> {
Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?))
}
pub fn read_u64(data: &[u8], at: usize) -> Option<u64> {
Some(u64::from_le_bytes(data.get(at..at + 8)?.try_into().ok()?))
}
+35
View File
@@ -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<object::read::Error> for PeError {
fn from(e: object::read::Error) -> Self {
PeError::Malformed(e.to_string())
}
}
/// `IMAGE_FILE_MACHINE_AMD64`.
pub const MACHINE_AMD64: u16 = 0x8664;
+20
View File
@@ -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
+130
View File
@@ -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<PathBuf>) -> Result<Self> {
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<PathBuf> {
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<Vec<u8>> {
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());
}
}
+23
View File
@@ -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<Vec<u8>>;
}
+15
View File
@@ -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
+179
View File
@@ -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<Part<'a>>,
}
const HEADER_SIZE: usize = 0x20;
const MAX_PARTS: usize = 256;
impl<'a> Container<'a> {
pub fn parse(data: &'a [u8]) -> Result<Self, ShaderError> {
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<u16, ShaderError> {
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<u32, ShaderError> {
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<u64, ShaderError> {
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<u8> {
let table = HEADER_SIZE + 4 * parts.len();
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
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());
}
}
+211
View File
@@ -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<Self, ShaderError> {
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<u8> {
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<u8> {
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());
}
}
+447
View File
@@ -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<u32>,
}
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<Vec<Instruction>, 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<Instruction> = 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<Flow, ShaderError> {
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<usize, Instruction>,
setpc: &Instruction,
len: usize,
) -> Result<Option<usize>, 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<Instruction, ShaderError> {
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::<Result<_, _>>()?,
})
}
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<u8> {
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());
}
}
File diff suppressed because it is too large. Load diff
+26
View File
@@ -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 },
}
+288
View File
@@ -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<u8>,
}
/// The native programs in a `DXIL` part's data; empty for the PC layout.
pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, 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<Vec<u8>, 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<Vec<NativeProgram>, 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<u8> {
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<u8> {
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<u8> {
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());
}
}
+57
View File
@@ -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.
+49
View File
@@ -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 <file> --invert-paths`), force-push, and have
everyone re-clone.
+5
View File
@@ -0,0 +1,5 @@
[toolchain]
channel = "1.98.1"
targets = ["x86_64-pc-windows-msvc"]
components = ["rustfmt", "clippy"]
profile = "minimal"
+2
View File
@@ -0,0 +1,2 @@
max_width = 100
use_field_init_shorthand = true
+7
View File
@@ -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"
+18
View File
@@ -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]
+4
View File
@@ -0,0 +1,4 @@
fn main() {
println!("cargo:rustc-link-arg-cdylib=/DELAYLOAD:victory-probe-delayed.dll");
println!("cargo:rustc-link-lib=delayimp");
}
+55
View File
@@ -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) }
}
+15
View File
@@ -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 = []
+16
View File
@@ -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
+56
View File
@@ -0,0 +1,56 @@
//! Repository maintenance. Run with `cargo xtask <command>`.
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()
}
+220
View File
@@ -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"!<arch>", "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<Vec<String>> {
let git = |args: &[&str]| -> Result<Option<Vec<String>>> {
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<String> {
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<usize> {
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());
}
}