diff --git a/README.md b/README.md index 66df93f9..90fe937a 100644 --- a/README.md +++ b/README.md @@ -104,8 +104,8 @@ inversion, and other bindings (see `xtp.example.toml`), by control: ## Commands ``` -xtp inspect [--imports] [--exports] -xtp census [paths...] [--missing] [--strict] +xtp inspect [--imports] [--exports] [--json] +xtp census [paths...] [--missing] [--strict] [--json] xtp lib-exports [--list] xtp shader-info [paths...] [--verbose] [--disasm] xtp translate [paths...] [--validate] [--pipelines] [--list] [--jobs N] @@ -114,6 +114,19 @@ xtp run [--execute] [--unimplemented trap|zero] [--strict] xtp config ``` +`xtp inspect --json` emits a stable JSON object (`"format": "xtp-inspect 1"`) +with string fields `file`, `blake3`, `kind` (`"exe"` or `"dll"`), hex-string +fields `machine`, `image_base` and `entry_rva`, numeric fields `subsystem` and +`size_of_image`, and an `imports` array of `{dll, symbol, delay, resolution}` +objects (`delay` is a boolean; `resolution` is `"hle"`, `"host"`, `"missing"`, +with `"title"` reserved because static `inspect` does not map title-shipped +DLLs, so those report as `"missing"`). `--json` ignores `--imports` and +`--exports`. `xtp census --json` emits `"format": "xtp-census 1"` with numeric +`images`, `unreadable`, `totals` (`{functions, hle, host, missing}`), a `dlls` +array (`{dll, functions, hle, host, missing, images}`), and always includes the +`missing` array (`{dll, symbol, images}`). The `format` version number +increments on any breaking schema change. + The title sees an Xbox Series S unless `--console series-x` or `XTP_CONSOLE=series-x` says otherwise: with Series S budgets the world loads in seconds, where Series X's push the host GPU's resident memory diff --git a/apps/xtp/src/census.rs b/apps/xtp/src/census.rs index ddf53946..8c9b2190 100644 --- a/apps/xtp/src/census.rs +++ b/apps/xtp/src/census.rs @@ -1,6 +1,7 @@ //! Which imports do titles need, and which do we cover? use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write; use std::io::Read; use std::path::{Path, PathBuf}; @@ -9,6 +10,8 @@ use xtp_hle::{HleResolver, HostPolicy}; use xtp_loader::Provenance; use xtp_pe::{ImageInfo, ImportSymbol}; +use crate::survey::quote; + #[derive(Default)] struct DllStats { functions: BTreeSet, @@ -18,7 +21,7 @@ struct DllStats { images: BTreeSet, } -pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> { +pub fn run(paths: Vec, strict: bool, list_missing: bool, json: bool) -> Result<()> { let paths = crate::default_paths(paths)?; let resolver = HleResolver::new(if strict { HostPolicy::none() @@ -77,6 +80,22 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> } } + let (mut f, mut h, mut o, mut m) = (0, 0, 0, 0); + for s in dlls.values() { + f += s.functions.len(); + h += s.hle; + o += s.host; + m += s.missing; + } + + if json { + print!( + "{}", + to_json(images, failed.len(), (f, h, o, m), &dlls, &missing) + ); + return Ok(()); + } + println!("{images} images scanned, {} unreadable", failed.len()); for (p, e) in &failed { println!(" skipped {}: {e}", p.display()); @@ -85,7 +104,6 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> "\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}", @@ -95,10 +113,6 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> 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"); @@ -113,6 +127,67 @@ pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> Ok(()) } +/// Stable JSON census report: totals, per-DLL counts, and missing pairs. +fn to_json( + images: usize, + unreadable: usize, + totals: (usize, usize, usize, usize), + dlls: &BTreeMap, + missing: &BTreeMap<(String, String), BTreeSet>, +) -> String { + let (functions, hle, host, missing_total) = totals; + let mut o = String::new(); + let _ = writeln!(o, "{{"); + let _ = writeln!(o, " \"format\": \"xtp-census 1\","); + let _ = writeln!(o, " \"images\": {images},"); + let _ = writeln!(o, " \"unreadable\": {unreadable},"); + let _ = writeln!( + o, + " \"totals\": {{\"functions\": {functions}, \"hle\": {hle}, \"host\": {host}, \"missing\": {missing_total}}}," + ); + + if dlls.is_empty() { + let _ = writeln!(o, " \"dlls\": [],"); + } else { + let _ = writeln!(o, " \"dlls\": ["); + for (i, (dll, s)) in dlls.iter().enumerate() { + let comma = if i + 1 < dlls.len() { "," } else { "" }; + let _ = writeln!( + o, + " {{\"dll\": {}, \"functions\": {}, \"hle\": {}, \"host\": {}, \"missing\": {}, \"images\": {}}}{comma}", + quote(dll), + s.functions.len(), + s.hle, + s.host, + s.missing, + s.images.len(), + ); + } + let _ = writeln!(o, " ],"); + } + + let mut rows: Vec<_> = missing.iter().collect(); + rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(b.0))); + if rows.is_empty() { + let _ = writeln!(o, " \"missing\": []"); + } else { + let _ = writeln!(o, " \"missing\": ["); + for (i, ((dll, sym), users)) in rows.iter().enumerate() { + let comma = if i + 1 < rows.len() { "," } else { "" }; + let _ = writeln!( + o, + " {{\"dll\": {}, \"symbol\": {}, \"images\": {}}}{comma}", + quote(dll), + quote(sym), + users.len(), + ); + } + let _ = writeln!(o, " ]"); + } + let _ = writeln!(o, "}}"); + o +} + /// Cheap pre-filter: an `MZ` header, regardless of extension (console /// packages do not always use .exe/.dll). fn looks_like_pe(path: &Path) -> bool { @@ -122,3 +197,16 @@ fn looks_like_pe(path: &Path) -> bool { .is_ok() && &magic == b"MZ" } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_census_json_emits_empty_arrays() { + let out = to_json(0, 0, (0, 0, 0, 0), &BTreeMap::new(), &BTreeMap::new()); + assert!(out.contains(r#""format": "xtp-census 1""#)); + assert!(out.contains(r#""dlls": []"#)); + assert!(out.contains(r#""missing": []"#)); + } +} diff --git a/apps/xtp/src/inspect.rs b/apps/xtp/src/inspect.rs index 7c0dbc08..8b2cc24f 100644 --- a/apps/xtp/src/inspect.rs +++ b/apps/xtp/src/inspect.rs @@ -1,14 +1,26 @@ use std::collections::BTreeMap; +use std::fmt::Write; use std::path::Path; use anyhow::{Context, Result}; +use xtp_hle::{HleResolver, HostPolicy}; +use xtp_loader::Provenance; use xtp_pe::implib::ImportLibrary; use xtp_pe::{ImageInfo, layout}; -pub fn run(file: &Path, list_imports: bool, list_exports: bool) -> Result<()> { +use crate::survey::quote; + +pub fn run(file: &Path, list_imports: bool, list_exports: bool, json: 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()))?; + if json { + let blake3 = blake3::hash(&data).to_hex().to_string(); + let resolver = HleResolver::new(HostPolicy::default()); + print!("{}", to_json(file, &blake3, &info, &resolver)); + return Ok(()); + } + println!("file {}", file.display()); println!("blake3 {}", blake3::hash(&data).to_hex()); if let Some(cv) = &info.codeview { @@ -151,3 +163,66 @@ fn dll_flags(v: u16) -> String { format!(" ({})", set.join(", ")) } } + +fn resolution_name(class: Option) -> &'static str { + match class { + Some(Provenance::Hle) => "hle", + Some(Provenance::Host) => "host", + Some(Provenance::Title) => "title", + None => "missing", + } +} + +/// Stable JSON summary of one PE image and how each import resolves. +fn to_json(file: &Path, blake3: &str, info: &ImageInfo, resolver: &HleResolver) -> String { + let mut o = String::new(); + let _ = writeln!(o, "{{"); + let _ = writeln!(o, " \"format\": \"xtp-inspect 1\","); + let _ = writeln!(o, " \"file\": {},", quote(&file.display().to_string())); + let _ = writeln!(o, " \"blake3\": {},", quote(blake3)); + let _ = writeln!( + o, + " \"kind\": {},", + quote(if info.is_dll() { "dll" } else { "exe" }) + ); + let _ = writeln!(o, " \"machine\": \"{:#06x}\",", info.machine); + let _ = writeln!(o, " \"subsystem\": {},", info.subsystem); + let _ = writeln!(o, " \"image_base\": \"{:#x}\",", info.image_base); + let _ = writeln!(o, " \"size_of_image\": {},", info.size_of_image); + let _ = writeln!(o, " \"entry_rva\": \"{:#x}\",", info.entry_rva); + + let mut rows: Vec<(String, String, bool, &'static str)> = Vec::new(); + for (delay, list) in [(false, &info.imports), (true, &info.delay_imports)] { + for module in list { + for entry in &module.entries { + let res = resolution_name(resolver.classify(&module.dll, &entry.symbol)); + rows.push((module.dll.clone(), entry.symbol.to_string(), delay, res)); + } + } + } + rows.sort_by(|a, b| { + a.0.to_ascii_lowercase() + .cmp(&b.0.to_ascii_lowercase()) + .then_with(|| a.1.cmp(&b.1)) + .then_with(|| a.2.cmp(&b.2)) + }); + + if rows.is_empty() { + let _ = writeln!(o, " \"imports\": []"); + } else { + let _ = writeln!(o, " \"imports\": ["); + for (i, (dll, sym, delay, res)) in rows.iter().enumerate() { + let comma = if i + 1 < rows.len() { "," } else { "" }; + let _ = writeln!( + o, + " {{\"dll\": {}, \"symbol\": {}, \"delay\": {delay}, \"resolution\": {}}}{comma}", + quote(dll), + quote(sym), + quote(res), + ); + } + let _ = writeln!(o, " ]"); + } + let _ = writeln!(o, "}}"); + o +} diff --git a/apps/xtp/src/main.rs b/apps/xtp/src/main.rs index 304a903f..9488e543 100644 --- a/apps/xtp/src/main.rs +++ b/apps/xtp/src/main.rs @@ -38,6 +38,9 @@ enum Command { /// List every exported function. #[arg(long)] exports: bool, + /// Emit stable JSON instead of the text summary. + #[arg(long)] + json: bool, }, /// Aggregate the imports of every PE image under the given paths and /// show which ones our runtime covers. Defaults to the configured @@ -50,6 +53,9 @@ enum Command { /// List every missing `dll!function`, most used first. #[arg(long)] missing: bool, + /// Emit stable JSON instead of the text table. + #[arg(long)] + json: bool, }, /// List the `dll!export` pairs an import library describes. LibExports { @@ -189,12 +195,14 @@ fn main() -> Result<()> { file, imports, exports, - } => inspect::run(&file, imports, exports), + json, + } => inspect::run(&file, imports, exports, json), Command::Census { paths, strict, missing, - } => census::run(paths, strict, missing), + json, + } => census::run(paths, strict, missing, json), Command::LibExports { lib, list } => inspect::lib_exports(&lib, list), Command::ShaderInfo { paths, diff --git a/apps/xtp/src/survey.rs b/apps/xtp/src/survey.rs index 059fc54e..5b22a442 100644 --- a/apps/xtp/src/survey.rs +++ b/apps/xtp/src/survey.rs @@ -853,7 +853,7 @@ fn stage_name(s: HwStage) -> &'static str { } /// A JSON string. -fn quote(s: &str) -> String { +pub(crate) fn quote(s: &str) -> String { let mut o = String::with_capacity(s.len() + 2); o.push('"'); for c in s.chars() { diff --git a/apps/xtp/tests/inspect_json.rs b/apps/xtp/tests/inspect_json.rs new file mode 100644 index 00000000..28b19fc8 --- /dev/null +++ b/apps/xtp/tests/inspect_json.rs @@ -0,0 +1,305 @@ +//! Integration tests for `xtp inspect --json` and `xtp census --json` on the +//! synthetic `hle-probe` fixture (no game files required). +#![cfg(windows)] + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") +} + +fn build_probe() -> PathBuf { + let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml"); + let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe-json"); + 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") +} + +/// Minimal JSON value + parser so tests validate syntax and structure +/// without adding a crate dependency. +#[derive(Debug, PartialEq)] +enum Json { + Null, + Bool(bool), + Number(i64), + Str(String), + Array(Vec), + Object(BTreeMap), +} + +impl Json { + fn as_object(&self) -> &BTreeMap { + match self { + Json::Object(map) => map, + other => panic!("expected JSON object, got {other:?}"), + } + } + + fn as_array(&self) -> &[Json] { + match self { + Json::Array(arr) => arr, + other => panic!("expected JSON array, got {other:?}"), + } + } + + fn as_str(&self) -> &str { + match self { + Json::Str(s) => s, + other => panic!("expected JSON string, got {other:?}"), + } + } + + fn as_i64(&self) -> i64 { + match self { + Json::Number(n) => *n, + other => panic!("expected JSON number, got {other:?}"), + } + } +} + +struct Parser<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Parser<'a> { + fn parse(input: &'a str) -> Json { + let mut p = Self { + bytes: input.as_bytes(), + pos: 0, + }; + let value = p.value(); + p.skip_ws(); + assert_eq!(p.pos, p.bytes.len(), "trailing bytes after JSON value"); + value + } + + fn skip_ws(&mut self) { + while let Some(&b) = self.bytes.get(self.pos) { + if matches!(b, b' ' | b'\n' | b'\r' | b'\t') { + self.pos += 1; + } else { + break; + } + } + } + + fn peek(&mut self) -> u8 { + self.skip_ws(); + *self.bytes.get(self.pos).expect("unexpected EOF in JSON") + } + + fn take(&mut self, expected: u8) { + let got = self.peek(); + assert_eq!( + got, expected, + "expected {:?}, got {:?} at byte {}", + expected as char, got as char, self.pos + ); + self.pos += 1; + } + + fn value(&mut self) -> Json { + match self.peek() { + b'{' => self.object(), + b'[' => self.array(), + b'"' => Json::Str(self.string()), + b't' => { + assert!(self.bytes[self.pos..].starts_with(b"true")); + self.pos += 4; + Json::Bool(true) + } + b'f' => { + assert!(self.bytes[self.pos..].starts_with(b"false")); + self.pos += 5; + Json::Bool(false) + } + b'n' => { + assert!(self.bytes[self.pos..].starts_with(b"null")); + self.pos += 4; + Json::Null + } + b'-' | b'0'..=b'9' => self.number(), + other => panic!("unexpected byte {:?} at {}", other as char, self.pos), + } + } + + fn object(&mut self) -> Json { + self.take(b'{'); + let mut map = BTreeMap::new(); + if self.peek() == b'}' { + self.pos += 1; + return Json::Object(map); + } + loop { + let key = self.string(); + self.take(b':'); + let val = self.value(); + assert!(map.insert(key, val).is_none(), "duplicate JSON key"); + match self.peek() { + b',' => self.pos += 1, + b'}' => { + self.pos += 1; + break; + } + other => panic!("expected ',' or '}}', got {:?}", other as char), + } + } + Json::Object(map) + } + + fn array(&mut self) -> Json { + self.take(b'['); + let mut items = Vec::new(); + if self.peek() == b']' { + self.pos += 1; + return Json::Array(items); + } + loop { + items.push(self.value()); + match self.peek() { + b',' => self.pos += 1, + b']' => { + self.pos += 1; + break; + } + other => panic!("expected ',' or ']', got {:?}", other as char), + } + } + Json::Array(items) + } + + fn string(&mut self) -> String { + self.take(b'"'); + let mut out = String::new(); + while let Some(&b) = self.bytes.get(self.pos) { + self.pos += 1; + match b { + b'"' => return out, + b'\\' => { + let esc = *self.bytes.get(self.pos).expect("EOF in escape"); + self.pos += 1; + match esc { + b'"' => out.push('"'), + b'\\' => out.push('\\'), + b'/' => out.push('/'), + b'n' => out.push('\n'), + b'r' => out.push('\r'), + b't' => out.push('\t'), + b'u' => { + let hex = std::str::from_utf8(&self.bytes[self.pos..self.pos + 4]) + .expect("unicode escape"); + self.pos += 4; + let code = u32::from_str_radix(hex, 16).expect("hex codepoint"); + out.push(char::from_u32(code).expect("valid char")); + } + other => panic!("unsupported escape \\{}", other as char), + } + } + other => out.push(other as char), + } + } + panic!("unterminated JSON string"); + } + + fn number(&mut self) -> Json { + let start = self.pos; + if self.bytes.get(self.pos) == Some(&b'-') { + self.pos += 1; + } + while matches!(self.bytes.get(self.pos), Some(b'0'..=b'9')) { + self.pos += 1; + } + let text = std::str::from_utf8(&self.bytes[start..self.pos]).expect("number utf8"); + Json::Number(text.parse().expect("valid integer")) + } +} + +#[test] +fn inspect_and_census_json_on_hle_probe() { + let probe = build_probe(); + let xtp = env!("CARGO_BIN_EXE_xtp"); + + let out = Command::new(xtp) + .args(["inspect", "--json"]) + .arg(&probe) + .output() + .expect("running xtp inspect --json"); + assert!( + out.status.success(), + "xtp inspect --json failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8(out.stdout).expect("utf8 stdout"); + let doc = Parser::parse(&stdout); + let obj = doc.as_object(); + assert_eq!(obj["format"].as_str(), "xtp-inspect 1"); + assert_eq!(obj["kind"].as_str(), "dll"); + assert!(obj["file"].as_str().ends_with("hle_probe.dll")); + assert_eq!(obj["machine"].as_str(), "0x8664"); + assert!(obj["image_base"].as_str().starts_with("0x")); + + let imports = obj["imports"].as_array(); + let has_hle_xgr = imports.iter().any(|item| { + let m = item.as_object(); + m["dll"].as_str().eq_ignore_ascii_case("xgameruntime.dll") + && m["resolution"].as_str() == "hle" + }); + assert!( + has_hle_xgr, + "expected xgameruntime.dll as hle in inspect --json: {stdout}" + ); + + let has_delayed_probe = imports.iter().any(|item| { + let m = item.as_object(); + m["dll"].as_str().contains("probe-delayed") && m["delay"] == Json::Bool(true) + }); + assert!( + has_delayed_probe, + "expected xtp-probe-delayed.dll with delay: true in inspect --json: {stdout}" + ); + + let has_missing_probe = imports.iter().any(|item| { + let m = item.as_object(); + m["dll"].as_str().contains("probe-missing") && m["resolution"].as_str() == "missing" + }); + assert!( + has_missing_probe, + "expected missing probe DLL as missing in inspect --json: {stdout}" + ); + + let census_out = Command::new(xtp) + .args(["census", "--json"]) + .arg(&probe) + .output() + .expect("running xtp census --json"); + assert!( + census_out.status.success(), + "xtp census --json failed: {}", + String::from_utf8_lossy(&census_out.stderr) + ); + let census_stdout = String::from_utf8(census_out.stdout).expect("utf8 stdout"); + let census = Parser::parse(&census_stdout); + let cobj = census.as_object(); + assert_eq!(cobj["format"].as_str(), "xtp-census 1"); + assert_eq!(cobj["images"].as_i64(), 1); + let totals = cobj["totals"].as_object(); + assert!(totals["hle"].as_i64() >= 1); + assert!(totals["missing"].as_i64() >= 1); + let missing_list = cobj["missing"].as_array(); + assert!( + missing_list + .iter() + .any(|item| item.as_object()["dll"].as_str().contains("probe-missing")), + "expected missing probe DLL in census --json: {census_stdout}" + ); +}