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

+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();
}
}