Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ inversion, and other bindings (see `xtp.example.toml`), by control:
## Commands

```
xtp inspect <exe|dll> [--imports] [--exports]
xtp census [paths...] [--missing] [--strict]
xtp inspect <exe|dll> [--imports] [--exports] [--json]
xtp census [paths...] [--missing] [--strict] [--json]
xtp lib-exports <import.lib> [--list]
xtp shader-info [paths...] [--verbose] [--disasm]
xtp translate [paths...] [--validate] [--pipelines] [--list] [--jobs N]
Expand All @@ -114,6 +114,19 @@ xtp run <exe> [--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
Expand Down
100 changes: 94 additions & 6 deletions apps/xtp/src/census.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand All @@ -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<ImportSymbol>,
Expand All @@ -18,7 +21,7 @@ struct DllStats {
images: BTreeSet<PathBuf>,
}

pub fn run(paths: Vec<PathBuf>, strict: bool, list_missing: bool) -> Result<()> {
pub fn run(paths: Vec<PathBuf>, strict: bool, list_missing: bool, json: bool) -> Result<()> {
let paths = crate::default_paths(paths)?;
let resolver = HleResolver::new(if strict {
HostPolicy::none()
Expand Down Expand Up @@ -77,6 +80,22 @@ pub fn run(paths: Vec<PathBuf>, 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());
Expand All @@ -85,7 +104,6 @@ pub fn run(paths: Vec<PathBuf>, 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}",
Expand All @@ -95,10 +113,6 @@ pub fn run(paths: Vec<PathBuf>, 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");

Expand All @@ -113,6 +127,67 @@ pub fn run(paths: Vec<PathBuf>, 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<String, DllStats>,
missing: &BTreeMap<(String, String), BTreeSet<PathBuf>>,
) -> 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 {
Expand All @@ -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": []"#));
}
}
77 changes: 76 additions & 1 deletion apps/xtp/src/inspect.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -151,3 +163,66 @@ fn dll_flags(v: u16) -> String {
format!(" ({})", set.join(", "))
}
}

fn resolution_name(class: Option<Provenance>) -> &'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
}
12 changes: 10 additions & 2 deletions apps/xtp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion apps/xtp/src/survey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Loading