Initial version
Rust validation / Windows x64 build and tests (push) Waiting to run
Rust validation / Formatting (push) Failing after 28s
EonaCat/ci-workflows: SonarQube / sonar (push) Successful in 47s

This commit is contained in:
EonaCat committed 2026-12-04 21:32:34 +01:00
1 parent 2cff35f215
commit fe8e2cb5e7
360 files changed
+253989 -74

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
use std::collections::{BTreeMap, BTreeSet};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use crate::hle::{HleResolver, HostPolicy};
use eonacat_xsbox_gpu::loader::Provenance;
use eonacat_xsbox_gpu::pe::{ImageInfo, ImportSymbol};
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum FunctionKey {
Name(String),
Ordinal(u16),
}
impl From<&ImportSymbol> for FunctionKey {
fn from(symbol: &ImportSymbol) -> Self {
match symbol {
ImportSymbol::Name { name, .. } => Self::Name(name.clone()),
ImportSymbol::Ordinal(ordinal) => Self::Ordinal(*ordinal),
}
}
}
#[derive(Default)]
struct DllStats {
functions: BTreeSet<FunctionKey>,
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 seen = BTreeSet::new();
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) {
let entry = match entry {
Ok(entry) => entry,
Err(error) if error.depth() == 0 => {
return Err(error).context("cannot scan census input");
}
Err(error) => {
failed.push(error.to_string());
continue;
}
};
let path = entry.path();
if !entry.file_type().is_file() {
continue;
}
match looks_like_pe(path) {
Ok(true) => {}
Ok(false) => continue,
Err(error) => {
failed.push(format!("{}: {error}", path.display()));
continue;
}
}
let identity = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
if !seen.insert(identity) {
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(format!("{}: {e}", path.display()));
continue;
}
};
images += 1;
tally_image(path, &info, &resolver, &mut dlls, &mut missing);
}
}
println!("{images} images scanned, {} unreadable", failed.len());
for error in &failed {
println!(" skipped {error}");
}
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(())
}
fn looks_like_pe(path: &Path) -> io::Result<bool> {
let mut magic = [0u8; 2];
match std::fs::File::open(path)?.read_exact(&mut magic) {
Ok(()) => Ok(&magic == b"MZ"),
Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => Ok(false),
Err(error) => Err(error),
}
}
fn tally_image(
path: &Path,
info: &ImageInfo,
resolver: &HleResolver,
dlls: &mut BTreeMap<String, DllStats>,
missing: &mut BTreeMap<(String, String), BTreeSet<PathBuf>>,
) {
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());
}
if stats.functions.insert(FunctionKey::from(&e.symbol)) {
match class {
Some(Provenance::Hle) => stats.hle += 1,
Some(Provenance::Host) => stats.host += 1,
Some(Provenance::Title) => unreachable!("census maps no title DLLs"),
None => stats.missing += 1,
}
}
}
}
}
+39
View File
@@ -0,0 +1,39 @@
use std::num::NonZeroUsize;
pub(crate) fn workers(requested: Option<usize>, work_items: Option<usize>) -> usize {
let available = std::thread::available_parallelism().map_or(2, NonZeroUsize::get);
let configured = std::env::var("EONACAT_XS_CPU_THREADS")
.ok()
.and_then(|value| value.trim().parse::<usize>().ok())
.filter(|&value| value > 0);
let count = requested
.filter(|&value| value > 0)
.or(configured)
.unwrap_or_else(|| (available / 2).max(1));
work_items.map_or(count, |items| count.min(items))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn never_returns_zero() {
assert!(workers(Some(0), None) >= 1);
assert_eq!(workers(Some(8), Some(0)), 0);
}
#[test]
fn explicit_value_is_not_silently_overridden() {
assert_eq!(workers(Some(3), Some(8)), 3);
}
#[test]
fn work_count_bounds_workers() {
assert_eq!(workers(Some(8), Some(2)), 2);
}
}
@@ -0,0 +1,57 @@
# Fetches the AMD files FSR 3 frame generation needs (about 30 MB) from AMD's own GitHub (the FidelityFX SDK,
# GPUOpen-LibrariesAndSDKs/FidelityFX-SDK) into a fidelityfx folder: by default amd-sdk\FidelityFX\bin here
# (git-ignored), where the EonaCat XS launcher looks for them; `eonacat-xsbox get-fsr` names one under
# %LOCALAPPDATA%\EonaCat\XS. They are AMD's, under AMD's licence (saved beside them: read it); this repository does
# not carry them, so each person gets them from AMD directly. Each file is checked against the SHA-256 of the
# copy this fork was tested with, and the game loads them only with AMD's valid signature.
param(
[string]$Tag = 'v2.4.0',
[string]$To = ''
)
$ProgressPreference = 'SilentlyContinue'
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
$bin = if ($To) { $To } else { Join-Path (Resolve-Path (Join-Path $PSScriptRoot '..')).Path 'amd-sdk\FidelityFX\bin' }
$base = "https://raw.githubusercontent.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/$Tag/Kits/FidelityFX"
# What the game loads, and the SHA-256 of the copies tested (FidelityFX SDK v2.4.0).
$files = [ordered]@{
'amd_fidelityfx_loader_dx12.dll' = 'E2191D3C0828BE45EB8AFFD4E3EC0378F2293ADC345B772A7170EDCF3B021ECB'
'amd_fidelityfx_framegeneration_dx12.dll' = 'E6843252F58B0341A0D80F6A20BC0D840643EE95BC48C22CAC08745344577BB6'
}
function Get-File([string]$Url, [string]$To) {
New-Item -ItemType Directory -Force (Split-Path $To) | Out-Null
$part = "$To.part"
if (Get-Command curl.exe -ErrorAction SilentlyContinue) {
& curl.exe --location --fail --silent --show-error --progress-bar --output $part $Url
if ($LASTEXITCODE -ne 0) { Remove-Item $part -ErrorAction SilentlyContinue; throw "could not get $Url" }
} else {
Invoke-WebRequest -Uri $Url -OutFile $part -UseBasicParsing -ErrorAction Stop
}
$part
}
Write-Host "AMD FSR 3 frame generation (FidelityFX SDK $Tag), from github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK (about 30 MB):"
New-Item -ItemType Directory -Force $bin | Out-Null
foreach ($name in $files.Keys) {
$to = Join-Path $bin $name
if ((Test-Path $to) -and (Get-FileHash $to -Algorithm SHA256).Hash -eq $files[$name]) {
Write-Host " $name already there"
continue
}
$part = Get-File "$base/signedbin/$name" $to
$hash = (Get-FileHash $part -Algorithm SHA256).Hash
if ($hash -ne $files[$name]) {
Remove-Item $part -Force
throw "$name is not the file this build was tested with (SHA-256 $hash); not kept"
}
Move-Item $part $to -Force
$len = (Get-Item $to).Length
Write-Host (" {0} {1}" -f $name, $(if ($len -ge 1MB) { '{0:N1} MB' -f ($len / 1MB) } else { '{0:N0} KB' -f ($len / 1KB) }))
}
try {
$lic = Get-File "$base/docs/license.md" (Join-Path $bin 'amd-fidelityfx-license.md')
Move-Item $lic (Join-Path $bin 'amd-fidelityfx-license.md') -Force
Write-Host " licence: $(Join-Path $bin 'amd-fidelityfx-license.md')"
} catch { Write-Host " (AMD's licence text could not be fetched: $($_.Exception.Message))" }
Write-Host ''
Write-Host 'Done. They are used from the next start.'
@@ -0,0 +1,62 @@
# Fetches Microsoft's newer Direct3D 12 runtime (the D3D12 Agility SDK, D3D12Core.dll, from Microsoft's own
# NuGet package Microsoft.Direct3D.D3D12, about 22 MB) into a D3D12 folder: by default the one beside
# target\release\eonacat-xsbox.exe; `eonacat-xsbox play` names the one beside itself. Windows 10's own Direct3D 12 stops at
# shader model 6.5, and every shader the layer translates is 6.6: without this runtime each pipeline is refused
# and the game closes within seconds. eonacat-xsbox.exe asks Windows for this runtime (it exports D3D12SDKVersion = 614
# and D3D12SDKPath = .\D3D12\); Windows uses it only where its own is older. It is Microsoft's, under Microsoft's
# licence (saved beside it: read it); this repository does not carry it. The package and the DLL are checked
# against the SHA-256 of the copies this fork was tested with, and the DLL against Microsoft's signature.
param(
[string]$Version = '1.614.1',
[string]$To = ''
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
$dir = if ($To) { $To } else { Join-Path (Resolve-Path (Join-Path $PSScriptRoot '..')).Path 'target\release\D3D12' }
# The SHA-256 of the copies tested: D3D12Core.dll 1.614.1.0 first, since launchers take the first hash after
# that name as the DLL's (VILauncher's "Fix and verify" took the package's and then refused every package).
$core = '8A23D826B25B4329522FF451CB52B7F2B34D7F2913CFEB878371CE8BD765FE2D'
# The package it comes in, Microsoft.Direct3D.D3D12 1.614.1.
$package = '9880AA91602DD51DD6CF7911A2BCA7A2323513B15338573CDE014B3356EEAFF2'
$url = "https://api.nuget.org/v3-flatcontainer/microsoft.direct3d.d3d12/$Version/microsoft.direct3d.d3d12.$Version.nupkg"
$target = Join-Path $dir 'D3D12Core.dll'
if ((Test-Path $target) -and (Get-FileHash $target -Algorithm SHA256).Hash -eq $core) {
Write-Host "Microsoft's Direct3D 12 runtime $Version is already in $dir"
exit 0
}
Write-Host "Microsoft's Direct3D 12 runtime $Version (the Agility SDK), from nuget.org (about 22 MB):"
New-Item -ItemType Directory -Force $dir | Out-Null
$part = Join-Path $dir "microsoft.direct3d.d3d12.$Version.nupkg.part"
try {
if (Get-Command curl.exe -ErrorAction SilentlyContinue) {
& curl.exe --location --fail --silent --show-error --progress-bar --output $part $url
if ($LASTEXITCODE -ne 0) { throw "could not get $url" }
} else {
Invoke-WebRequest -Uri $url -OutFile $part -UseBasicParsing
}
$hash = (Get-FileHash $part -Algorithm SHA256).Hash
if ($hash -ne $package) { throw "the package is not the one this build was tested with (SHA-256 $hash); not kept" }
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip = [IO.Compression.ZipFile]::OpenRead($part)
try {
$entry = $zip.Entries | Where-Object FullName -eq 'build/native/bin/x64/D3D12Core.dll'
if (-not $entry) { throw 'the package has no build/native/bin/x64/D3D12Core.dll' }
$dll = "$target.part"
[IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $dll, $true)
$lic = $zip.Entries | Where-Object FullName -eq 'LICENSE.txt'
if ($lic) { [IO.Compression.ZipFileExtensions]::ExtractToFile($lic, (Join-Path $dir 'microsoft-d3d12-license.txt'), $true) }
} finally { $zip.Dispose() }
$hash = (Get-FileHash $dll -Algorithm SHA256).Hash
if ($hash -ne $core) { Remove-Item $dll -Force; throw "D3D12Core.dll is not the file this build was tested with (SHA-256 $hash); not kept" }
$sig = Get-AuthenticodeSignature $dll
if ($sig.Status -ne 'Valid' -or $sig.SignerCertificate.Subject -notlike 'CN=Microsoft Corporation,*') {
Remove-Item $dll -Force; throw "D3D12Core.dll is not validly signed by Microsoft ($($sig.Status)); not kept"
}
Move-Item $dll $target -Force
} finally {
Remove-Item $part -Force -ErrorAction SilentlyContinue
}
Write-Host (' D3D12Core.dll {0:N1} MB, signed by Microsoft' -f ((Get-Item $target).Length / 1MB))
Write-Host " in $dir (licence: microsoft-d3d12-license.txt beside it)"
@@ -0,0 +1,159 @@
# Fetches the NVIDIA files DLSS and DLSS frame generation need (about 70 MB) from NVIDIA's own GitHub into
# nvidia-sdk\Streamline\bin\x64 here (git-ignored), where the EonaCat XS launcher looks for them. They are
# NVIDIA's, under NVIDIA's licences (saved beside them: read them); this repository does not and may not carry
# them, so each person gets them from NVIDIA directly. the launcher invokes this embedded installer through the engine command.
# Nothing of NVIDIA's is needed to build the layer: the files are loaded when the game runs.
param(
[string]$StreamlineTag = 'v2.14.16',
# Another folder for them than nvidia-sdk here (`eonacat-xsbox get-dlss` names one under %LOCALAPPDATA%\EonaCat\XS).
[string]$To = '',
# Skip the signature check below (only if NVIDIA's files fail it for a reason you have looked into).
[switch]$SkipSignatureCheck
)
$ProgressPreference = 'SilentlyContinue' # Invoke-WebRequest's progress bar makes it many times slower
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
$sdk = if ($To) { $To } else { Join-Path (Resolve-Path (Join-Path $PSScriptRoot '..')).Path 'nvidia-sdk' }
$sl = Join-Path $sdk 'Streamline'
$bin = Join-Path $sl 'bin\x64'
# What is loaded when the game runs: Streamline's interposer and plugins, DLSS and the frame generation model.
$dlls = 'sl.interposer.dll', 'sl.common.dll', 'sl.dlss.dll', 'sl.dlss_g.dll', 'sl.reflex.dll', 'sl.pcl.dll', 'nvngx_dlss.dll', 'nvngx_dlssg.dll'
# One file from a URL, with curl's progress line where Windows has curl (it has since Windows 10 1803).
function Get-File([string]$Url, [string]$To) {
New-Item -ItemType Directory -Force (Split-Path $To) | Out-Null
$part = "$To.part"
if (Get-Command curl.exe -ErrorAction SilentlyContinue) {
& curl.exe --location --fail --silent --show-error --progress-bar --output $part $Url
if ($LASTEXITCODE -ne 0) { Remove-Item $part -ErrorAction SilentlyContinue; throw "could not get $Url" }
} else {
Invoke-WebRequest -Uri $Url -OutFile $part -UseBasicParsing -ErrorAction Stop
}
Move-Item $part $To -Force
}
# Bytes first..last of a URL.
function Get-Range([string]$Url, [long]$First, [long]$Last) {
$q = [Net.HttpWebRequest]::Create($Url)
$q.UserAgent = 'get-nvidia-sdks'
$q.AddRange($First, $Last)
$r = $q.GetResponse()
try {
if ([int]$r.StatusCode -ne 206) { throw 'the server does not give parts of the file' }
$m = New-Object IO.MemoryStream
$r.GetResponseStream().CopyTo($m)
, $m.ToArray()
} finally { $r.Close() }
}
# Takes the named files out of a zip on a server without downloading the whole zip: its directory is at
# its end, and each file in it can be asked for by its place. $Want: a regex on the paths in the zip.
# Each goes into $Into under the part of its path after the SDK's top folder.
function Get-FromZip([string]$Url, [string]$Want, [string]$Into) {
# Where the file really is (the download address redirects), and how long it is.
$h = [Net.HttpWebRequest]::Create($Url); $h.Method = 'HEAD'; $h.UserAgent = 'get-nvidia-sdks'
$r = $h.GetResponse(); $real = $r.ResponseUri.AbsoluteUri; $length = $r.ContentLength; $r.Close()
$tailLen = [Math]::Min($length, 2MB)
$tail = Get-Range $real ($length - $tailLen) ($length - 1)
$end = -1
for ($i = $tail.Length - 22; $i -ge 0; $i--) {
if ($tail[$i] -eq 0x50 -and $tail[$i + 1] -eq 0x4b -and $tail[$i + 2] -eq 5 -and $tail[$i + 3] -eq 6) { $end = $i; break }
}
if ($end -lt 0) { throw 'no zip directory found' }
$dirSize = [BitConverter]::ToUInt32($tail, $end + 12)
$dirAt = [BitConverter]::ToUInt32($tail, $end + 16)
if ($dirAt -eq [uint32]::MaxValue) { throw 'a zip64 archive' }
$dir = if ($dirAt -ge $length - $tailLen) {
$from = [int]($dirAt - ($length - $tailLen)); , $tail[$from..($from + $dirSize - 1)]
} else { Get-Range $real $dirAt ($dirAt + $dirSize - 1) }
$got = 0
$at = 0
while ($at + 46 -le $dir.Length -and [BitConverter]::ToUInt32($dir, $at) -eq 0x02014b50) {
$method = [BitConverter]::ToUInt16($dir, $at + 10)
$packed = [BitConverter]::ToUInt32($dir, $at + 20)
$size = [BitConverter]::ToUInt32($dir, $at + 24)
$nameLen = [BitConverter]::ToUInt16($dir, $at + 28)
$extraLen = [BitConverter]::ToUInt16($dir, $at + 30)
$noteLen = [BitConverter]::ToUInt16($dir, $at + 32)
$headerAt = [BitConverter]::ToUInt32($dir, $at + 42)
$name = [Text.Encoding]::UTF8.GetString($dir, $at + 46, $nameLen)
$at += 46 + $nameLen + $extraLen + $noteLen
if ($name -notmatch $Want) { continue }
# The file's own header (its extra field may be longer than the directory's), then its bytes.
$piece = Get-Range $real $headerAt ($headerAt + 30 + $nameLen + 2048 + $packed - 1)
if ([BitConverter]::ToUInt32($piece, 0) -ne 0x04034b50) { throw "no file header for $name" }
$dataAt = 30 + [BitConverter]::ToUInt16($piece, 26) + [BitConverter]::ToUInt16($piece, 28)
if ($dataAt + $packed -gt $piece.Length) { throw "the header of $name is longer than expected" }
$out = [IO.MemoryStream]::new()
if ($method -eq 0) { $out.Write($piece, $dataAt, [int]$packed) }
elseif ($method -eq 8) {
$in = [IO.MemoryStream]::new($piece, $dataAt, [int]$packed)
$z = [IO.Compression.DeflateStream]::new($in, [IO.Compression.CompressionMode]::Decompress)
$z.CopyTo($out); $z.Close()
} else { throw "$name is packed in a way this script does not know ($method)" }
if ($out.Length -ne $size) { throw "$name came out $($out.Length) bytes long, not $size" }
$rel = ($name -replace '^.*?(?=(bin/x64/|license\.txt$))', '') -replace '/', '\'
$to = Join-Path $Into $rel
New-Item -ItemType Directory -Force (Split-Path $to) | Out-Null
[IO.File]::WriteAllBytes($to, $out.ToArray())
Write-Host (" {0} {1:N1} MB" -f $rel, ($size / 1MB))
$got++
}
$got
}
# These DLLs are loaded into the game's process, so each one must carry a valid Authenticode signature
# from NVIDIA before it is kept. A file that fails is deleted, so a bad download is never used by accident.
function Assert-NvidiaSigned([string[]]$Names) {
if ($SkipSignatureCheck) { Write-Host ' signature check skipped (-SkipSignatureCheck)'; return }
$bad = @()
foreach ($n in $Names) {
$f = Join-Path $bin $n
if (-not (Test-Path $f)) { continue }
$sig = Get-AuthenticodeSignature -FilePath $f
$who = if ($sig.SignerCertificate) { $sig.SignerCertificate.Subject } else { '' }
if ($sig.Status -ne 'Valid' -or $who -notmatch 'NVIDIA') {
$bad += "$n ($($sig.Status)$(if ($who) { ', ' + $who }))"
Remove-Item $f -Force -ErrorAction SilentlyContinue
}
}
if ($bad) { throw "Not signed by NVIDIA, removed: $($bad -join '; '). Run again, or see -SkipSignatureCheck." }
Write-Host ' signatures: all valid, signed by NVIDIA'
}
Write-Host "NVIDIA Streamline $StreamlineTag with DLSS and frame generation, from github.com/NVIDIA-RTX/Streamline (about 70 MB):"
$missing = @($dlls | Where-Object { -not (Test-Path (Join-Path $bin $_)) })
if (-not $missing) {
Write-Host " all there already: $bin"
} else {
$url = "https://github.com/NVIDIA-RTX/Streamline/releases/download/$StreamlineTag/streamline-sdk-$StreamlineTag.zip"
$names = ($dlls | ForEach-Object { [regex]::Escape($_) }) -join '|'
$want = "(^|/)bin/x64/($names|[^/]*license[^/]*\.txt)$|^([^/]+/)?license\.txt$"
try { [void](Get-FromZip $url $want $sl) }
catch { Write-Host " Taking the files out of the archive in place did not work ($($_.Exception.Message))." }
if (@($dlls | Where-Object { -not (Test-Path (Join-Path $bin $_)) })) {
# The whole archive then (263 MB).
Write-Host ' Getting the whole archive instead (263 MB) ...'
$zip = Join-Path $sdk "streamline-sdk-$StreamlineTag.zip"
Get-File $url $zip
$into = Join-Path $sdk 'streamline-unpacked'
Expand-Archive -Path $zip -DestinationPath $into -Force -ErrorAction Stop
$found = Get-ChildItem $into -Recurse -Filter 'sl.interposer.dll' |
Where-Object { $_.FullName -match '\\bin\\x64\\sl\.interposer\.dll$' -and $_.FullName -notmatch '\\development\\' } |
Select-Object -First 1
if (-not $found) { throw 'The Streamline archive has no bin\x64\sl.interposer.dll.' }
$top = Split-Path (Split-Path (Split-Path $found.FullName))
New-Item -ItemType Directory -Force $bin | Out-Null
Get-ChildItem (Join-Path $top 'bin\x64') -File |
Where-Object { $dlls -contains $_.Name -or $_.Name -match 'license.*\.txt$' } |
Copy-Item -Destination $bin -Force
Copy-Item (Join-Path $top 'license.txt') $sl -Force -ErrorAction SilentlyContinue
Remove-Item $into -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item $zip -Force
}
}
Assert-NvidiaSigned $dlls
$still = @($dlls | Where-Object { -not (Test-Path (Join-Path $bin $_)) })
if ($still) { throw "Not there after all: $($still -join ', ')" }
Write-Host " licences: $(Join-Path $sl 'license.txt') (Streamline) and the *.license.txt files in $bin (DLSS, Reflex)"
Write-Host ''
Write-Host 'Done. They are used from the next start.'
+127
View File
@@ -0,0 +1,127 @@
use anyhow::{Context, Result, ensure};
use eonacat_xsbox_gpu::loader::PreparedImage;
use super::native_1440p::{RETAIL_BUILD, same};
const SERIES_X_TABLE: u32 = 0x0618_6250 + 0x50;
const RT_HEAP: u32 = SERIES_X_TABLE + 8 + 2 * 8;
const STOCK_TOTAL: u64 = 13_312 << 20;
const STOCK_RT_HEAP: u64 = 2_199 << 20;
pub(super) fn rt_heap_asked() -> Option<u64> {
let mb: u64 = std::env::var("EONACAT_XS_RT_HEAP_MB").ok()?.trim().parse().ok()?;
let bytes = mb.checked_mul(1 << 20)?;
(bytes > STOCK_RT_HEAP && mb <= 24 * 1024).then_some(bytes)
}
pub(super) fn prepare_rt_heap(image: &mut PreparedImage, bytes: u64) -> Result<()> {
ensure!(
image.original_hash.to_hex().as_str() == RETAIL_BUILD,
"the render-target heap is only known for the retail build {RETAIL_BUILD}"
);
let total = u64::from_le_bytes(*field::<8>(image, SERIES_X_TABLE)?);
let heap = u64::from_le_bytes(*field::<8>(image, RT_HEAP)?);
ensure!(
total == STOCK_TOTAL && heap == STOCK_RT_HEAP,
"the Series X heap table is not the stock one (total {total:#x}, heap 2 {heap:#x})"
);
ensure!(bytes > heap, "the render-target heap asked for is not bigger than the stock one");
*field::<8>(image, RT_HEAP)? = bytes.to_le_bytes();
*field::<8>(image, SERIES_X_TABLE)? = (total + (bytes - heap)).to_le_bytes();
Ok(())
}
const SCENE_POOL_UNITS: u32 = 0x01d4_88ac;
const STOCK_SCENE_POOL: &str = "24ee573f2d52472e3a964bcf583618cb9f02f00ec4d9d98735fdab6bd3034a88";
const STOCK_UNITS: u32 = 0x2c60;
pub(super) fn scene_pool_asked() -> Option<u32> {
let mb: u32 = std::env::var("EONACAT_XS_SCENE_POOL_MB").ok()?.trim().parse().ok()?;
let units = mb.checked_mul(16)?;
(units > STOCK_UNITS && units <= 0xffff).then_some(units)
}
pub(super) fn prepare_scene_pool(image: &mut PreparedImage, units: u32) -> Result<u32> {
ensure!(
image.original_hash.to_hex().as_str() == RETAIL_BUILD,
"the scene pool is only known for the retail build {RETAIL_BUILD}"
);
ensure!(units > STOCK_UNITS && units <= 0xffff, "the scene pool asked for is not bigger than the stock one");
ensure!(same(&field::<10>(image, SCENE_POOL_UNITS)?[..], STOCK_SCENE_POOL), "unexpected scene pool unit counts");
let array = relocate_unit_array(image, units)?;
field::<10>(image, SCENE_POOL_UNITS)?[6..10].copy_from_slice(&units.to_le_bytes());
Ok(array)
}
const UNIT_ARRAY_LEAS: [(u32, &str); 4] = [
(0x0247_3fa1, "b7518a48bc0007deaa9966263959502315c9561f0fbc5ef8bb2623f6f104ab2a"),
(0x0247_4079, "16882fd85dc4b9c44488bb550045230deb00eadcb0221819e2a1b67b845321bb"),
(0x0247_40ec, "4a927d3bf20744b6f3eb7094de6a6ac4fb05b379da6857c8e201b614de915c4a"),
(0x05eb_278d, "91f9b4974217482cdbfa4505b428080afa2e8b1fb49d5e8b22983da0ef30bdf8"),
];
fn relocate_unit_array(image: &mut PreparedImage, units: u32) -> Result<u32> {
for &(rva, stock) in &UNIT_ARRAY_LEAS {
ensure!(same(&field::<7>(image, rva)?[..], stock), "the scene pool's array is not taken where the stock image takes it (+{rva:#x})");
}
let section = add_section(image, b".vicpool", units as usize * 8 + 0x1000)?;
for &(rva, _) in &UNIT_ARRAY_LEAS {
let disp = i32::try_from(i64::from(section) - (i64::from(rva) + 7)).context("the new array is out of reach")?;
field::<7>(image, rva)?[3..7].copy_from_slice(&disp.to_le_bytes());
}
Ok(section)
}
fn add_section(image: &mut PreparedImage, name: &[u8; 8], size: usize) -> Result<u32> {
const UNINITIALISED_READ_WRITE: u32 = 0xc000_0080;
let b = &mut image.bytes;
let u16_at = |b: &[u8], o: usize| b.get(o..o + 2).map(|v| u16::from_le_bytes([v[0], v[1]]));
let u32_at = |b: &[u8], o: usize| b.get(o..o + 4).map(|v| u32::from_le_bytes([v[0], v[1], v[2], v[3]]));
let short = "incomplete image headers";
let pe = u32_at(b, 0x3c).context(short)? as usize;
ensure!(b.get(pe..pe + 4) == Some(b"PE\0\0".as_slice()), "no PE header");
let file = pe + 4;
let count = usize::from(u16_at(b, file + 2).context(short)?);
let optional = file + 20;
ensure!(u16_at(b, optional) == Some(0x20b), "not a PE32+ image");
let align = u32_at(b, optional + 32).context(short)?;
ensure!(align.is_power_of_two(), "unexpected section alignment");
let size_of_image_at = optional + 56;
let headers = u32_at(b, optional + 60).context(short)? as usize;
let table = optional + usize::from(u16_at(b, file + 16).context(short)?);
let slot = table + count * 40;
ensure!(slot + 40 <= headers && headers <= b.len(), "no room in the headers for another section");
ensure!(b[slot..slot + 40].iter().all(|&x| x == 0), "the next section header slot is not empty");
let end = (0..count)
.filter_map(|i| u32_at(b, table + i * 40 + 12)?.checked_add(u32_at(b, table + i * 40 + 8)?))
.max()
.context("no sections")?;
let rva = end.checked_next_multiple_of(align).context("image too big")?;
ensure!(Some(rva) == u32_at(b, size_of_image_at), "the last section does not end at the image's size");
let virtual_size = u32::try_from(size).ok().and_then(|s| s.checked_next_multiple_of(align)).context("section too big")?;
let new_size = rva.checked_add(virtual_size).context("image too big")?;
b[slot..slot + 8].copy_from_slice(name);
b[slot + 8..slot + 12].copy_from_slice(&virtual_size.to_le_bytes());
b[slot + 12..slot + 16].copy_from_slice(&rva.to_le_bytes());
b[slot + 36..slot + 40].copy_from_slice(&UNINITIALISED_READ_WRITE.to_le_bytes());
b[file + 2..file + 4].copy_from_slice(&u16::try_from(count + 1).context("too many sections")?.to_le_bytes());
b[size_of_image_at..size_of_image_at + 4].copy_from_slice(&new_size.to_le_bytes());
image.info.size_of_image = new_size;
Ok(rva)
}
fn field<const N: usize>(image: &mut PreparedImage, rva: u32) -> Result<&mut [u8; N]> {
let offset = image.info.rva_to_file_offset(rva).context("memory budget field missing")? as usize;
image
.bytes
.get_mut(offset..offset + N)
.context("incomplete memory budget field")?
.try_into()
.context("invalid memory budget field length")
}
+83
View File
@@ -0,0 +1,83 @@
pub fn asked() -> bool {
asked_for(std::env::var("EONACAT_XS_KEEP_AWAKE").ok().as_deref())
}
fn asked_for(value: Option<&str>) -> bool {
value != Some("0")
}
#[cfg(windows)]
#[must_use = "the request is let go as soon as the guard is dropped"]
pub struct Awake {
request: *mut std::ffi::c_void,
}
#[cfg(not(windows))]
#[must_use = "the request is let go as soon as the guard is dropped"]
pub struct Awake;
#[cfg(windows)]
pub fn hold() -> Option<Awake> {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Power::{
PowerCreateRequest, PowerRequestDisplayRequired, PowerRequestSystemRequired,
PowerSetRequest,
};
use windows_sys::Win32::System::Threading::{
POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT,
};
let mut reason: Vec<u16> = "eonacat-xs: the title is running\0".encode_utf16().collect();
let mut context = REASON_CONTEXT {
Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
..Default::default()
};
context.Reason.SimpleReasonString = reason.as_mut_ptr();
let request = unsafe { PowerCreateRequest(&context) };
if request.is_null() || request as isize == -1 {
tracing::info!("the screen's power request was not created");
return None;
}
for flag in [PowerRequestDisplayRequired, PowerRequestSystemRequired] {
if unsafe { PowerSetRequest(request, flag) } == 0 {
tracing::info!(flag, "the screen's power request was refused");
unsafe {
windows_sys::Win32::System::Power::PowerClearRequest(
request,
PowerRequestDisplayRequired,
);
CloseHandle(request);
}
return None;
}
}
Some(Awake { request })
}
#[cfg(not(windows))]
pub fn hold() -> Option<Awake> {
None
}
#[cfg(windows)]
impl Drop for Awake {
fn drop(&mut self) {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Power::{
PowerClearRequest, PowerRequestDisplayRequired, PowerRequestSystemRequired,
};
unsafe {
for flag in [PowerRequestDisplayRequired, PowerRequestSystemRequired] {
PowerClearRequest(self.request, flag);
}
CloseHandle(self.request);
}
}
}
+82
View File
@@ -0,0 +1,82 @@
use windows_sys::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING};
use windows_sys::Win32::System::Console::{
AllocConsole, FreeConsole, GetConsoleWindow, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
SetStdHandle,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
SW_HIDE, SW_RESTORE, SW_SHOW, SetForegroundWindow, ShowWindow,
};
use windows_sys::core::w;
pub fn hide() {
if std::env::var_os("EONACAT_XS_CONSOLE").is_some_and(|v| v == "1") {
return;
}
unsafe {
let hwnd = GetConsoleWindow();
if hwnd.is_null() {
return;
}
ShowWindow(hwnd, SW_HIDE);
}
tracing::info!("console hidden (F5 shows it)");
}
pub fn show() {
unsafe {
let mut hwnd = GetConsoleWindow();
if hwnd.is_null() {
FreeConsole();
if AllocConsole() == 0 {
tracing::warn!("F5: could not open a console window");
return;
}
attach_std_handles();
hwnd = GetConsoleWindow();
if hwnd.is_null() {
return;
}
}
ShowWindow(hwnd, SW_SHOW);
ShowWindow(hwnd, SW_RESTORE);
SetForegroundWindow(hwnd);
}
tracing::info!("console shown (F5)");
}
unsafe fn attach_std_handles() {
unsafe {
let out = CreateFileW(
w!("CONOUT$"),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
std::ptr::null(),
OPEN_EXISTING,
0,
std::ptr::null_mut(),
);
if out != INVALID_HANDLE_VALUE {
SetStdHandle(STD_OUTPUT_HANDLE, out);
SetStdHandle(STD_ERROR_HANDLE, out);
}
let input = CreateFileW(
w!("CONIN$"),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
std::ptr::null(),
OPEN_EXISTING,
0,
std::ptr::null_mut(),
);
if input != INVALID_HANDLE_VALUE {
SetStdHandle(STD_INPUT_HANDLE, input);
}
}
}
+165
View File
@@ -0,0 +1,165 @@
use eonacat_xsbox_gpu::pe::ImportSymbol;
#[derive(Debug, Clone)]
pub struct HostPolicy {
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",
"sspicli.dll",
"cabinet.dll",
"avrt.dll",
"ext-ms-win-rtcore-ntuser-*",
"api-ms-win-shcore-*",
"msvcp_win.dll",
"ole32.dll",
"advapi32.dll",
"iphlpapi.dll",
"dbghelp.dll",
"xaudio2_9.dll",
"mfplat.dll",
"mfreadwrite.dll",
];
HostPolicy {
allow: allow.iter().map(|s| s.to_string()).collect(),
}
}
}
pub(crate) fn is_bare_dll_name(dll: &str) -> bool {
!dll.is_empty() && dll != "." && dll != ".." && !dll.contains(['\\', '/', ':', '\0'])
}
impl HostPolicy {
pub fn none() -> Self {
HostPolicy { allow: Vec::new() }
}
pub fn allows(&self, dll: &str) -> bool {
if !is_bare_dll_name(dll) {
return false;
}
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;
}
let address = imp::resolve(dll, symbol)?;
#[cfg(windows)]
if let ImportSymbol::Name { name, .. } = symbol {
let ours = eonacat_xsbox_gpu::titlewrite::import(name, address);
let ours = eonacat_xsbox_gpu::heap_hooks::import(name, ours);
if ours != address {
return Some(ours);
}
}
#[cfg(all(windows, feature = "diagnostics"))]
if let ImportSymbol::Name { name, .. } = symbol {
return Some(eonacat_xsbox_gpu::timeline::import(name, address));
}
Some(address)
}
}
pub(crate) fn function(dll: &str, name: &str) -> Option<usize> {
let name = ImportSymbol::Name {
hint: 0,
name: name.into(),
};
imp::resolve(dll, &name)
}
#[cfg(windows)]
mod imp {
use std::collections::HashMap;
use std::ffi::CString;
use std::sync::{LazyLock, Mutex};
use eonacat_xsbox_gpu::pe::ImportSymbol;
use windows_sys::Win32::System::LibraryLoader::{
GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA,
};
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()?;
unsafe { GetProcAddress(module as _, name.as_ptr().cast()) }
}
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> {
if !super::is_bare_dll_name(dll) {
return None;
}
let key = dll.to_ascii_lowercase();
let cache = || MODULES.lock().unwrap_or_else(|e| e.into_inner());
let cached = cache().get(&key).copied();
if cached.is_some() {
return cached;
}
let name = CString::new(key.as_str()).ok()?;
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: &eonacat_xsbox_gpu::pe::ImportSymbol) -> Option<usize> {
None
}
}
+123
View File
@@ -0,0 +1,123 @@
use std::time::Duration;
struct Word {
name: String,
offset: usize,
bytes: usize,
}
fn words(text: &str) -> Vec<Word> {
text.split(',')
.filter_map(|part| {
let (name, rest) = part.trim().split_once('=')?;
let (offset, bytes) = rest.split_once(':').unwrap_or((rest, "8"));
let offset = usize::from_str_radix(offset.trim().trim_start_matches("0x"), 16).ok()?;
let bytes = bytes.trim().parse().ok().filter(|n| matches!(n, 1 | 2 | 4 | 8))?;
Some(Word { name: name.trim().to_owned(), offset, bytes })
})
.collect()
}
fn held(text: &str) -> Vec<(Word, u64)> {
text.split(',')
.filter_map(|part| {
let (word, value) = part.trim().rsplit_once('=')?;
let value = value.trim();
let value = match value.strip_prefix("0x") {
Some(hex) => u64::from_str_radix(hex, 16).ok()?,
None => value.parse().ok()?,
};
Some((words(word).pop()?, value))
})
.collect()
}
fn write(base: usize, word: &Word, value: u64) -> bool {
use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let bytes = value.to_le_bytes();
let ok = unsafe {
WriteProcessMemory(GetCurrentProcess(), (base + word.offset) as *mut _, bytes.as_ptr().cast(), word.bytes, std::ptr::null_mut())
};
ok != 0
}
fn hold(base: usize) {
let Ok(text) = std::env::var("EONACAT_XS_IMAGE_HOLD") else {
return;
};
let held = held(&text);
if base == 0 || held.is_empty() {
return;
}
let names: Vec<String> = held.iter().map(|(word, value)| format!("{}={value}", word.name)).collect();
tracing::info!("the title's image: holding {} (EONACAT_XS_IMAGE_HOLD)", names.join(" "));
let _ = std::thread::Builder::new().name("eonacat-xs-image-hold".into()).spawn(move || {
let mut failed = false;
loop {
for (word, value) in &held {
if !write(base, word, *value) && !failed {
failed = true;
tracing::warn!(word = %word.name, "the title's image: a held word cannot be written (EONACAT_XS_IMAGE_HOLD)");
}
}
std::thread::sleep(Duration::from_millis(100));
}
});
}
fn read(base: usize, word: &Word) -> Option<u64> {
use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let mut value = [0u8; 8];
let ok = unsafe {
ReadProcessMemory(
GetCurrentProcess(),
(base + word.offset) as *const _,
value.as_mut_ptr().cast(),
word.bytes,
std::ptr::null_mut(),
)
};
(ok != 0).then(|| u64::from_le_bytes(value))
}
pub(crate) fn start(base: usize) {
static HOLDING: std::sync::Once = std::sync::Once::new();
HOLDING.call_once(|| hold(base));
let Ok(text) = std::env::var("EONACAT_XS_IMAGE_WATCH") else {
return;
};
let words = words(&text);
if base == 0 || words.is_empty() {
return;
}
static STARTED: std::sync::Once = std::sync::Once::new();
STARTED.call_once(|| {
let _ = std::thread::Builder::new().name("eonacat-xs-image-watch".into()).spawn(move || {
let mut last = Vec::new();
loop {
std::thread::sleep(Duration::from_secs(1));
let now: Vec<Option<u64>> = words.iter().map(|word| read(base, word)).collect();
if now == last {
continue;
}
let values: Vec<String> = words
.iter()
.zip(&now)
.map(|(word, value)| match value {
Some(value) => format!("{}={value:#x}", word.name),
None => format!("{}=?", word.name),
})
.collect();
tracing::info!("the title's image: {}", values.join(" "));
last = now;
}
});
});
}
+85
View File
@@ -0,0 +1,85 @@
mod host;
mod image_watch;
#[cfg(windows)]
pub use eonacat_xsbox_gpu::frame::decline_coupled_interval;
#[cfg(all(windows, feature = "diagnostics"))]
pub use eonacat_xsbox_gpu::frame_phase;
pub use eonacat_xsbox_gpu::memory_model;
pub use eonacat_xsbox_gpu::frames_begun;
#[cfg(windows)]
pub use eonacat_xsbox_gpu::cpu_mirror_files;
pub mod awake;
#[cfg(windows)]
pub mod console_window;
pub mod modules;
#[cfg(windows)]
pub mod mousehook;
mod registry;
pub mod runtime;
pub use host::HostPolicy;
pub use registry::{HleExport, HleModule, registry};
pub use eonacat_xsbox_gpu::console;
#[cfg(windows)]
pub use eonacat_xsbox_gpu::dxr;
#[cfg(windows)]
pub use eonacat_xsbox_gpu::streamline;
pub use eonacat_xsbox_gpu::save_share;
#[cfg(windows)]
pub use eonacat_xsbox_gpu::start_notice;
#[cfg(windows)]
pub use eonacat_xsbox_gpu::reserve_upload_space;
#[cfg(all(windows, feature = "diagnostics"))]
pub use eonacat_xsbox_gpu::replay;
#[cfg(windows)]
pub use eonacat_xsbox_gpu::pipeline::known as known_pipelines;
#[cfg(windows)]
pub use eonacat_xsbox_gpu::heap_hooks;
use eonacat_xsbox_gpu::loader::{ImportResolver, Provenance, Resolution};
use eonacat_xsbox_gpu::pe::ImportSymbol;
#[derive(Debug, Default)]
pub struct HleResolver {
pub host: HostPolicy,
}
impl HleResolver {
pub fn new(host: HostPolicy) -> Self {
HleResolver { host }
}
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 Some(address) = registry::lookup(dll, &symbol.to_string()) {
return Resolution::Found {
address,
provenance: Provenance::Hle,
};
}
match self.host.resolve(dll, symbol) {
Some(address) => Resolution::Found {
address,
provenance: Provenance::Host,
},
None => Resolution::Missing,
}
}
}
+614
View File
@@ -0,0 +1,614 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::alloc::Layout;
use std::collections::VecDeque;
use std::ffi::c_void;
use std::sync::Mutex;
use opus_pure::OpusDecoder;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent};
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{HRESULT, S_OK};
use crate::hle::{HleModule};
use crate::hle_export;
const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
const QUEUE_FULL: HRESULT = 0x8AC8_1000_u32 as i32;
pub(crate) const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32;
const INVALID_COMMAND: HRESULT = 0x8AC8_1002_u32 as i32;
const INVALID_STREAM: HRESULT = 0x8AC8_1003_u32 as i32;
const ALREADY_ACTIVE: HRESULT = 0x8AC8_1005_u32 as i32;
const BAD_PACKET: HRESULT = 0x8AC8_1008_u32 as i32;
const DECODE_OPUS: u32 = 1;
const DECODE_CONVERT_OPUS: u32 = 2;
const CONVERT_PCM: u32 = 3;
const ACTIVATE: u32 = 1;
const DEACTIVATE: u32 = 2;
const PROCESS: u32 = 3;
const NOTIFY: u32 = 4;
const RESET: u32 = 5;
const SIGNAL: u32 = 1;
const FLUSH: u32 = 2;
const RESET_DECODER: u32 = 4;
const DEINTERLEAVED_INPUT: u32 = 2;
const DEINTERLEAVED_OUTPUT: u32 = 4;
const RESULT_EVENT: u32 = 8;
const MAX_FRAMES: usize = 5760;
#[repr(C)]
pub struct ConnectInput {
process: u32,
streams: u32,
commands_per_stream: u32,
memory: u32,
frames_per_output: u32,
options: u32,
}
#[repr(C)]
pub struct ConnectOutput {
memory: *mut c_void,
result_event: HANDLE,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct CommandId {
kind: u32,
stream: u32,
sequence: u32,
options: u32,
context: u64,
}
#[repr(C, packed)]
struct Activate {
id: CommandId,
channels: u32,
init_length: u32,
init: *const c_void,
start_pitch: f32,
processing_length: u32,
processing: *mut c_void,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
struct Process {
id: CommandId,
pitch_ramp: f32,
target_pitch: f32,
first_frame: u32,
frame_count: u32,
input_length: u32,
input: *const u8,
output_length: u32,
output: *mut u8,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct ApuResult {
id: CommandId,
state: u32,
state_data: u64,
usec: u64,
error: HRESULT,
frames: u32,
output_length: u32,
output: *mut u8,
pitch: f32,
input_length: u32,
input: *const u8,
}
unsafe impl Send for ApuResult {}
pub struct Connection {
memory: *mut u8,
layout: Layout,
event: HANDLE,
options: u32,
per_stream: u32,
process: u32,
chunk: usize,
state: Mutex<State>,
}
struct State {
streams: Vec<Option<Stream>>,
queued: Vec<u32>,
results: VecDeque<ApuResult>,
commands: u32,
dequeued: u32,
}
fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> {
c.state.lock().unwrap_or_else(|e| e.into_inner())
}
pub extern "system" fn XApuConnect(
input: *const ConnectInput,
output: *mut ConnectOutput,
handle: *mut *mut Connection,
) -> HRESULT {
if input.is_null() || output.is_null() || handle.is_null() {
return E_INVALIDARG;
}
let input = unsafe { &*input };
if !(1..=500).contains(&input.streams)
|| !(1..=16).contains(&input.commands_per_stream)
|| input.memory == 0
{
return E_INVALIDARG;
}
match (input.process, input.frames_per_output) {
(DECODE_OPUS, 0) => {}
(DECODE_CONVERT_OPUS | CONVERT_PCM, 256 | 480 | 512 | 960 | 1024) => {}
(DECODE_OPUS | DECODE_CONVERT_OPUS | CONVERT_PCM, _) => return E_INVALIDARG,
(process, _) => {
tracing::warn!(process, "audio decoder: unknown processing kind");
return E_NOTIMPL;
}
}
let Ok(layout) = Layout::from_size_align(input.memory as usize, 16) else {
return E_INVALIDARG;
};
let memory = unsafe { std::alloc::alloc_zeroed(layout) };
if memory.is_null() {
return E_OUTOFMEMORY;
}
let event = if input.options & RESULT_EVENT != 0 {
let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) };
if event.is_null() {
unsafe { std::alloc::dealloc(memory, layout) };
return E_OUTOFMEMORY;
}
event
} else {
std::ptr::null_mut()
};
let streams = input.streams as usize;
tracing::info!(
streams,
memory = input.memory,
options = input.options,
"audio decoder connected"
);
let connection = Box::new(Connection {
memory,
layout,
event,
options: input.options,
per_stream: input.commands_per_stream,
process: input.process,
chunk: input.frames_per_output as usize,
state: Mutex::new(State {
streams: (0..streams).map(|_| None).collect(),
queued: vec![0; streams],
results: VecDeque::new(),
commands: 0,
dequeued: 0,
}),
});
unsafe {
output.write(ConnectOutput {
memory: memory.cast(),
result_event: event,
});
handle.write(Box::into_raw(connection));
}
S_OK
}
pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT {
if handle.is_null() {
return E_INVALIDARG;
}
let connection = unsafe { Box::from_raw(handle) };
if !connection.event.is_null() {
unsafe { CloseHandle(connection.event) };
}
unsafe { std::alloc::dealloc(connection.memory, connection.layout) };
S_OK
}
pub extern "system" fn XApuEnqueueCommand(
handle: *mut Connection,
command: *const CommandId,
total: *mut u32,
) -> HRESULT {
if handle.is_null() || command.is_null() {
return E_INVALIDARG;
}
let (connection, id) = unsafe { (&*handle, command.read_unaligned()) };
let mut state = lock(connection);
let stream = id.stream as usize;
if stream >= state.streams.len() {
return INVALID_STREAM;
}
if state.queued[stream] >= connection.per_stream {
return QUEUE_FULL;
}
let mut result = ApuResult {
id,
state: 0,
state_data: 0,
usec: 0,
error: S_OK,
frames: 0,
output_length: 0,
output: std::ptr::null_mut(),
pitch: 1.0,
input_length: 0,
input: std::ptr::null(),
};
let slot = &mut state.streams[stream];
match id.kind {
ACTIVATE => {
let activate = unsafe { command.cast::<Activate>().read_unaligned() };
let (channels, start_pitch) = (activate.channels, activate.start_pitch);
tracing::debug!(stream, channels, process = connection.process, "audio stream activated");
result.error = if slot.is_some() {
ALREADY_ACTIVE
} else {
match Stream::new(connection.process, channels, start_pitch) {
Some(s) => {
*slot = Some(s);
S_OK
}
None => E_INVALIDARG,
}
};
}
DEACTIVATE => {
*slot = None;
#[cfg(feature = "diagnostics")]
opus_log(handle, stream, None);
}
RESET => {
if let Some(s) = slot {
s.reset(id.options & RESET_DECODER != 0);
}
}
NOTIFY => {}
PROCESS => {
let command = unsafe { command.cast::<Process>().read_unaligned() };
match slot {
Some(Stream { decoder: Some(d), converter: None, .. }) => {
process(d, connection.options, &command, &mut result);
}
Some(s) => s.convert(connection, &command, &mut result),
None => result.error = INVALID_STREAM,
}
#[cfg(feature = "diagnostics")]
opus_log(handle, stream, Some(result.frames));
}
_ => return INVALID_COMMAND,
}
state.queued[stream] += 1;
state.commands = state.commands.wrapping_add(1);
state.results.push_back(result);
if !total.is_null() {
unsafe { total.write(state.commands) };
}
if id.options & SIGNAL != 0 && !connection.event.is_null() {
unsafe { SetEvent(connection.event) };
}
S_OK
}
struct Stream {
decoder: Option<OpusDecoder>,
converter: Option<Converter>,
}
impl Stream {
fn new(process: u32, channels: u32, start_pitch: f32) -> Option<Stream> {
if !(1..=2).contains(&channels) {
return None;
}
let channels = channels as usize;
let decoder = match process {
CONVERT_PCM => None,
_ => Some(OpusDecoder::new(48_000, channels).ok()?),
};
let converter = (process != DECODE_OPUS).then(|| Converter::new(channels, start_pitch));
Some(Stream { decoder, converter })
}
fn reset(&mut self, decoder_only: bool) {
if let Some(d) = &mut self.decoder {
let _ = d.reset_state();
}
if let Some(c) = &mut self.converter
&& !decoder_only
{
c.reset();
}
}
fn convert(&mut self, connection: &Connection, command: &Process, result: &mut ApuResult) {
let Some(converter) = &mut self.converter else {
result.error = INVALID_STREAM;
return;
};
let channels = converter.channels;
let (input, input_length) = (command.input, command.input_length);
let (output, output_length) = (command.output, command.output_length);
(result.input, result.input_length, result.output) = (input, input_length, output);
if input.is_null() || output.is_null() {
result.error = E_INVALIDARG;
return;
}
let bytes = unsafe { std::slice::from_raw_parts(input, input_length as usize) };
let frames: Vec<f32> = match &mut self.decoder {
Some(decoder) => {
let mut pcm = vec![0f32; MAX_FRAMES * channels];
let Ok(decoded) = decoder.decode(bytes, MAX_FRAMES, &mut pcm) else {
result.error = BAD_PACKET;
return;
};
let first = (command.first_frame as usize).min(decoded);
let count = (decoded - first).min(command.frame_count as usize);
pcm[first * channels..(first + count) * channels].to_vec()
}
None => {
let samples: Vec<f32> = bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect();
let count = samples.len() / channels;
if connection.options & DEINTERLEAVED_INPUT != 0 && channels == 2 {
(0..count).flat_map(|i| [samples[i], samples[count + i]]).collect()
} else {
samples[..count * channels].to_vec()
}
}
};
let unconverted_before = converter.input.len() / channels;
converter.input.extend_from_slice(&frames);
let used = converter.run(command.target_pitch, command.pitch_ramp);
let used_here = used.min(unconverted_before + frames.len() / channels);
let chunk = connection.chunk;
let deinterleaved = connection.options & DEINTERLEAVED_OUTPUT != 0 && channels == 2;
let ready = converter.output.len() / channels;
let flush = command.id.options & FLUSH != 0;
let mut give = if ready >= chunk { chunk } else if flush { ready } else { 0 };
let room = output_length as usize / 4;
give = give.min(if deinterleaved { room.saturating_sub(chunk).min(chunk) } else { room / channels });
let out: Vec<f32> = converter.output.drain(..give * channels).collect();
let write = |at: usize, v: f32| unsafe { output.add(at * 4).cast::<[u8; 4]>().write_unaligned(v.to_le_bytes()) };
for i in 0..give {
if deinterleaved {
write(i, out[2 * i]);
write(chunk + i, out[2 * i + 1]);
} else {
for c in 0..channels {
write(i * channels + c, out[i * channels + c]);
}
}
}
let left = converter.output.len() / channels;
result.frames = give as u32;
result.output_length = match (give, deinterleaved) {
(0, _) => 0,
(_, true) => ((chunk + give) * 4) as u32,
_ => (give * channels * 4) as u32,
};
result.pitch = converter.pitch;
result.state = (u32::from(give > 0) * OUTPUT_READY)
| if left >= chunk { MORE_OUTPUT_AVAILABLE } else { NEED_MORE_INPUT };
let kept = (converter.input.len() / channels) as u64;
result.state_data = (left as u64).min(0xffff) | (used_here as u64).min(0xffff) << 16 | kept.min(0xffff) << 48;
}
}
const OUTPUT_READY: u32 = 1;
const NEED_MORE_INPUT: u32 = 2;
const MORE_OUTPUT_AVAILABLE: u32 = 4;
const PITCHES: std::ops::RangeInclusive<f32> = 0.125..=8.0;
struct Converter {
channels: usize,
start_pitch: f32,
pitch: f32,
input: Vec<f32>,
pos: f64,
output: VecDeque<f32>,
}
impl Converter {
fn new(channels: usize, start_pitch: f32) -> Converter {
let start_pitch = if start_pitch.is_finite() { start_pitch.clamp(*PITCHES.start(), *PITCHES.end()) } else { 1.0 };
Converter { channels, start_pitch, pitch: start_pitch, input: Vec::new(), pos: 0.0, output: VecDeque::new() }
}
fn reset(&mut self) {
*self = Converter::new(self.channels, self.start_pitch);
}
fn run(&mut self, target: f32, ramp: f32) -> usize {
let channels = self.channels;
let frames = self.input.len() / channels;
let target = if target.is_finite() { target.clamp(*PITCHES.start(), *PITCHES.end()) } else { self.pitch };
let ramp = ramp.abs();
while (self.pos as usize) + 1 < frames {
let i = self.pos as usize;
let t = (self.pos - i as f64) as f32;
for c in 0..channels {
let (a, b) = (self.input[i * channels + c], self.input[(i + 1) * channels + c]);
self.output.push_back(a + (b - a) * t);
}
self.pos += f64::from(self.pitch);
self.pitch = if ramp == 0.0 {
target
} else if self.pitch < target {
(self.pitch + ramp).min(target)
} else {
(self.pitch - ramp).max(target)
};
}
let used = (self.pos as usize).min(frames);
self.input.drain(..used * channels);
self.pos -= used as f64;
used
}
}
#[cfg(feature = "diagnostics")]
fn opus_log(connection: *const Connection, stream: usize, frames: Option<u32>) {
use std::collections::BTreeMap;
use std::time::Instant;
type Log = (Option<Instant>, BTreeMap<(usize, usize), u64>);
static LOG: Mutex<Log> = Mutex::new((None, BTreeMap::new()));
let Some(ms) = super::audio::voice_log_ms() else {
return;
};
let mut log = LOG.lock().unwrap_or_else(|e| e.into_inner());
let key = (connection as usize, stream);
let Some(frames) = frames else {
log.1.remove(&key);
return;
};
*log.1.entry(key).or_default() += u64::from(frames);
if log.0.is_some_and(|t| t.elapsed().as_millis() < ms) {
return;
}
log.0 = Some(Instant::now());
for (&(connection, stream), &frames) in &log.1 {
tracing::info!(
connection = format_args!("{connection:#x}"),
stream,
frames,
"Opus stream position"
);
}
}
fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) {
let channels = decoder.channels();
let (input, input_length) = (command.input, command.input_length);
let (output, output_length) = (command.output, command.output_length);
result.input = input;
result.input_length = input_length;
result.output = output;
if input.is_null() || output.is_null() || input_length == 0 {
result.error = E_INVALIDARG;
return;
}
let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) };
let mut pcm = vec![0f32; MAX_FRAMES * channels];
let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) {
Ok(n) => n,
Err(_) => {
result.error = BAD_PACKET;
return;
}
};
let first = (command.first_frame as usize).min(decoded);
let frames = (decoded - first)
.min(command.frame_count as usize)
.min(output_length as usize / (4 * channels));
let kept = &pcm[first * channels..(first + frames) * channels];
let bytes = frames * channels * 4;
if bytes > 0 {
let out = unsafe { std::slice::from_raw_parts_mut(output, bytes) };
if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 {
let (left, right) = out.split_at_mut(frames * 4);
let (left, _) = left.as_chunks_mut::<4>();
let (right, _) = right.as_chunks_mut::<4>();
for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() {
left[i] = frame[0].to_le_bytes();
right[i] = frame[1].to_le_bytes();
}
} else {
for (dst, &sample) in out.as_chunks_mut::<4>().0.iter_mut().zip(kept) {
*dst = sample.to_le_bytes();
}
}
}
result.frames = frames as u32;
result.output_length = bytes as u32;
}
pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT {
if handle.is_null() || out.is_null() {
return E_INVALIDARG;
}
let mut state = lock(unsafe { &*handle });
let Some(result) = state.results.pop_front() else {
return PENDING_RESULTS;
};
let stream = result.id.stream as usize;
state.queued[stream] -= 1;
state.dequeued = state.dequeued.wrapping_add(1);
unsafe { out.write_unaligned(result) };
S_OK
}
pub extern "system" fn XApuGetResultCount(handle: *mut Connection, total: *mut u32) -> u32 {
if handle.is_null() {
return 0;
}
let state = lock(unsafe { &*handle });
if !total.is_null() {
unsafe { total.write(state.dequeued) };
}
state.results.len() as u32
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "apu",
dlls: &["xapu.dll"],
exports: vec![
hle_export!(XApuConnect),
hle_export!(XApuDisconnect),
hle_export!(XApuEnqueueCommand),
hle_export!(XApuDequeueResult),
hle_export!(XApuGetResultCount),
],
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,214 @@
use std::fs::File;
use std::io::{Seek, SeekFrom, Write};
use std::path::Path;
use std::time::{Duration, Instant};
use windows::Win32::Media::Audio::{
AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK,
AUDIOCLIENT_ACTIVATION_PARAMS, AUDIOCLIENT_ACTIVATION_PARAMS_0,
AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS,
ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation,
IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl,
IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX,
};
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx};
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::System::Threading::{
OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject,
};
use windows::core::{HRESULT, IUnknown, Interface, Ref, implement};
const RATE: u32 = 48_000;
const FRAME_BYTES: usize = 4;
#[implement(IActivateAudioInterfaceCompletionHandler)]
struct Activated;
impl IActivateAudioInterfaceCompletionHandler_Impl for Activated_Impl {
fn ActivateCompleted(
&self,
_: Ref<IActivateAudioInterfaceAsyncOperation>,
) -> windows::core::Result<()> {
Ok(())
}
}
const TARGET: &str = "EONACAT_XS_AUDIO_CAPTURE_OF";
pub fn start() {
if tracing::enabled!(tracing::Level::DEBUG) {
let _ = std::thread::Builder::new()
.name("eonacat-xsbox timing probe".into())
.spawn(|| {
loop {
std::thread::sleep(Duration::from_secs(1));
let at = Instant::now();
unsafe { Sleep(1) };
let ms = at.elapsed().as_secs_f32() * 1000.0;
tracing::debug!(ms, "Sleep(1) took");
}
});
}
if std::env::var_os("EONACAT_XS_AUDIO_CAPTURE").is_some()
&& let Err(e) = std::env::current_exe().and_then(|exe| {
std::process::Command::new(exe)
.env(TARGET, std::process::id().to_string())
.spawn()
})
{
tracing::warn!("audio capture not started: {e}");
}
}
pub fn child() -> bool {
let (Some(pid), Some(path)) = (
std::env::var(TARGET).ok().and_then(|p| p.parse().ok()),
std::env::var_os("EONACAT_XS_AUDIO_CAPTURE"),
) else {
return false;
};
if let Err(e) = record(pid, Path::new(&path)) {
tracing::warn!("audio capture stopped: {e}");
}
true
}
fn header(frames: u64) -> [u8; 44] {
let data = u32::try_from(frames * FRAME_BYTES as u64).unwrap_or(u32::MAX - 36);
let mut h = [0u8; 44];
let fields: [(&[u8], usize); 11] = [
(b"RIFF", 0),
(&(36 + data).to_le_bytes(), 4),
(b"WAVEfmt ", 8),
(&16u32.to_le_bytes(), 16),
(&1u16.to_le_bytes(), 20),
(&2u16.to_le_bytes(), 22),
(&RATE.to_le_bytes(), 24),
(&(RATE * FRAME_BYTES as u32).to_le_bytes(), 28),
(&(FRAME_BYTES as u16).to_le_bytes(), 32),
(&16u16.to_le_bytes(), 34),
(b"data", 36),
];
for (bytes, at) in fields {
h[at..at + bytes.len()].copy_from_slice(bytes);
}
h[40..].copy_from_slice(&data.to_le_bytes());
h
}
fn record(pid: u32, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
unsafe {
CoInitializeEx(None, COINIT_MULTITHREADED).ok()?;
let target = OpenProcess(PROCESS_SYNCHRONIZE, false, pid)?;
let params = AUDIOCLIENT_ACTIVATION_PARAMS {
ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {
ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {
TargetProcessId: pid,
ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
},
},
};
#[repr(C)]
struct Blob {
vt: u16,
reserved: [u16; 3],
size: u32,
data: *const AUDIOCLIENT_ACTIVATION_PARAMS,
}
let blob = Blob {
vt: 0x41,
reserved: [0; 3],
size: size_of_val(&params) as u32,
data: &params,
};
let handler: IActivateAudioInterfaceCompletionHandler = Activated.into();
let operation = ActivateAudioInterfaceAsync(
VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,
&IAudioClient::IID,
Some((&raw const blob).cast()),
&handler,
)?;
let client = loop {
let (mut hr, mut client) = (HRESULT(0), None::<IUnknown>);
if operation.GetActivateResult(&mut hr, &mut client).is_ok() {
hr.ok()?;
break client.ok_or("no audio client")?.cast::<IAudioClient>()?;
}
std::thread::sleep(Duration::from_millis(10));
};
let format = WAVEFORMATEX {
wFormatTag: WAVE_FORMAT_PCM as u16,
nChannels: 2,
nSamplesPerSec: RATE,
nAvgBytesPerSec: RATE * FRAME_BYTES as u32,
nBlockAlign: FRAME_BYTES as u16,
wBitsPerSample: 16,
cbSize: 0,
};
client.Initialize(
AUDCLNT_SHAREMODE_SHARED,
AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
10_000_000,
0,
&format,
None,
)?;
let capture: IAudioCaptureClient = client.GetService()?;
let mut file = File::create(path)?;
file.write_all(&header(0))?;
client.Start()?;
tracing::info!(path = %path.display(), "recording the title's audio");
let (mut written, mut first) = (0u64, None);
let mut patched = Instant::now();
loop {
std::thread::sleep(Duration::from_millis(10));
let ended = WaitForSingleObject(target, 0) == WAIT_OBJECT_0;
while capture.GetNextPacketSize()? > 0 {
let (mut data, mut frames, mut flags, mut qpc) = (std::ptr::null_mut(), 0, 0, 0);
capture.GetBuffer(&mut data, &mut frames, &mut flags, None, Some(&mut qpc))?;
let at = (qpc - *first.get_or_insert(qpc)) * u64::from(RATE) / 10_000_000;
if at > written + u64::from(RATE / 500) {
tracing::debug!(
ms = (at - written) * 1000 / u64::from(RATE),
"audio capture: nothing played"
);
let silence = vec![0u8; (at - written) as usize * FRAME_BYTES];
file.write_all(&silence)?;
written = at;
}
let bytes = frames as usize * FRAME_BYTES;
if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 {
file.write_all(&vec![0u8; bytes])?;
} else {
file.write_all(std::slice::from_raw_parts(data, bytes))?;
}
if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 && written > 0 {
tracing::debug!("audio capture: discontinuity");
}
written += u64::from(frames);
capture.ReleaseBuffer(frames)?;
}
if ended || patched.elapsed() >= Duration::from_secs(1) {
file.seek(SeekFrom::Start(0))?;
file.write_all(&header(written))?;
file.seek(SeekFrom::End(0))?;
patched = Instant::now();
}
if ended {
return Ok(());
}
}
}
}
@@ -0,0 +1,42 @@
use windows::Win32::Media::Audio::{IMMDeviceEnumerator, MMDeviceEnumerator, eConsole, eRender};
use windows::Win32::System::Com::{
CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize,
};
use windows::core::HRESULT;
const E_NOTFOUND: HRESULT = HRESULT(0x8007_0490_u32 as i32);
pub const NO_OUTPUT_NOTICE: [&str; 3] = [
"NO AUDIO OUTPUT: THE GAME FREEZES WHEN LOADING",
"TURN ON A PLAYBACK DEVICE (EVEN A VIRTUAL ONE)",
"IN WINDOWS SOUND SETTINGS, THEN START AGAIN",
];
pub fn has_playback_device() -> Option<bool> {
std::thread::Builder::new()
.name("eonacat-xsbox audio output check".into())
.spawn(ask)
.ok()?
.join()
.ok()
.flatten()
}
fn ask() -> Option<bool> {
unsafe {
CoInitializeEx(None, COINIT_MULTITHREADED).ok().ok()?;
let answer = CoCreateInstance::<_, IMMDeviceEnumerator>(&MMDeviceEnumerator, None, CLSCTX_ALL)
.ok()
.and_then(|devices| match devices.GetDefaultAudioEndpoint(eRender, eConsole) {
Ok(_) => Some(true),
Err(e) if e.code() == E_NOTFOUND => Some(false),
Err(_) => None,
});
CoUninitialize();
answer
}
}
+419
View File
@@ -0,0 +1,419 @@
use std::collections::HashMap;
use std::ffi::OsStr;
use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Instant;
use eonacat_xsbox_gpu::loader::{ImportResolver, Provenance, Resolution};
use eonacat_xsbox_gpu::pe::ImportSymbol;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
enum Mode {
Off,
NotLooping,
All,
Intro,
}
fn parse_mode(value: Option<&OsStr>) -> Mode {
let Some(value) = value.and_then(OsStr::to_str) else {
return Mode::Off;
};
match value.trim() {
"" | "0" => Mode::Off,
"1" => Mode::NotLooping,
v if v.eq_ignore_ascii_case("all") => Mode::All,
v if v.eq_ignore_ascii_case("intro") => Mode::Intro,
v => {
tracing::warn!(
value = v,
"EONACAT_XS_SKIP_BINK: expected 1, intro or all; not skipping"
);
Mode::Off
}
}
}
#[repr(C)]
#[allow(dead_code)]
struct Movie {
width: u32,
height: u32,
frames: u32,
frame_num: u32,
last_frame_num: u32,
frame_rate: u32,
frame_rate_div: u32,
read_error: u32,
open_flags: u32,
}
const _: () = assert!(std::mem::offset_of!(Movie, open_flags) == 0x20);
const WILL_LOOP: u32 = 0x80;
const NAMES: [&str; 12] = [
"BinkClose",
"BinkWait",
"BinkShouldSkip",
"BinkDoFrame",
"BinkDoFrameAsync",
"BinkDoFrameAsyncMulti",
"BinkDoFrameAsyncWait",
"BinkNextFrame",
"BinkGoto",
"BinkPause",
"BinkCopyToBuffer",
"BinkCopyToBufferRect",
];
const CLOSE: usize = 0;
const PAUSE: usize = 9;
type Export = extern "system" fn(*mut Movie, usize, usize, usize) -> usize;
const WRAPPERS: [Export; 10] = [
close,
wait,
should_skip,
do_frame,
do_frame_async,
do_frame_async_multi,
do_frame_async_wait,
next_frame,
goto,
pause,
];
const COPIES: [Copy; 2] = [copy_to_buffer, copy_to_buffer_rect];
static ORIGINALS: [AtomicUsize; 12] = [const { AtomicUsize::new(0) }; 12];
static MODE: AtomicU8 = AtomicU8::new(Mode::Off as u8);
static MOVIES: Mutex<Option<HashMap<usize, bool>>> = Mutex::new(None);
pub fn wrap(dll: &str, name: &str, address: usize) -> usize {
static FROM_ENV: OnceLock<Mode> = OnceLock::new();
let mode = *FROM_ENV.get_or_init(|| {
let mode = parse_mode(std::env::var_os("EONACAT_XS_SKIP_BINK").as_deref());
if mode != Mode::Off {
tracing::info!(?mode, "Bink movies are skipped");
}
mode
});
wrap_with(mode, dll, name, address)
}
fn wrap_with(mode: Mode, dll: &str, name: &str, address: usize) -> usize {
let is_bink = dll
.get(..4)
.is_some_and(|start| start.eq_ignore_ascii_case("bink"));
if !is_bink || address == 0 {
return address;
}
if name == "BinkRegisterFrameBuffers" {
if REGISTER.compare_exchange(0, address, Ordering::AcqRel, Ordering::Acquire).is_err_and(|bound| bound != address) {
return address;
}
return register_frame_buffers as *const () as usize;
}
let Some(i) = NAMES.iter().position(|&n| n == name) else {
return address;
};
let first = ORIGINALS[i].compare_exchange(0, address, Ordering::AcqRel, Ordering::Acquire);
if first.is_err_and(|bound| bound != address) {
tracing::warn!(dll, name, "a second Bink DLL: its movies are not skipped");
return address;
}
MODE.store(mode as u8, Ordering::Relaxed);
match WRAPPERS.get(i) {
Some(&w) => w as usize,
None => COPIES[i - WRAPPERS.len()] as usize,
}
}
static CALLS: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12];
static CALL_US: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12];
static CALL_MAX_US: [AtomicU64; 12] = [const { AtomicU64::new(0) }; 12];
fn timed<T>(i: usize, call: impl FnOnce() -> T) -> T {
let began = Instant::now();
let result = call();
let us = began.elapsed().as_micros() as u64;
CALLS[i].fetch_add(1, Ordering::Relaxed);
CALL_US[i].fetch_add(us, Ordering::Relaxed);
CALL_MAX_US[i].fetch_max(us, Ordering::Relaxed);
let n = CALLS[i].load(Ordering::Relaxed);
if n == 1 || n.is_power_of_two() {
tracing::info!(
export = NAMES[i], calls = n, total_ms = CALL_US[i].load(Ordering::Relaxed) as f64 / 1000.0,
average_us = CALL_US[i].load(Ordering::Relaxed) as f64 / n as f64,
max_ms = CALL_MAX_US[i].load(Ordering::Relaxed) as f64 / 1000.0,
"Bink export timing (wall time; async start and wait are separate)"
);
}
result
}
fn forward(i: usize, movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
let address = ORIGINALS[i].load(Ordering::Acquire);
let original: Export = unsafe { std::mem::transmute::<usize, Export>(address) };
if (3..=6).contains(&i) {
timed(i, || original(movie, a, b, c))
} else {
original(movie, a, b, c)
}
}
static REGISTER: AtomicUsize = AtomicUsize::new(0);
static PLANES: Mutex<Option<HashMap<usize, Vec<(usize, usize)>>>> = Mutex::new(None);
extern "system" fn register_frame_buffers(movie: *mut Movie, buffers: usize, b: usize, c: usize) -> usize {
if !movie.is_null() && buffers != 0 {
let mut bytes = vec![0u8; 24 + 4 * 5 * 24];
let mut got = 0usize;
unsafe {
windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory(
windows_sys::Win32::System::Threading::GetCurrentProcess(),
buffers as *const _,
bytes.as_mut_ptr().cast(),
bytes.len(),
&mut got,
)
};
let word = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap_or_default());
let (total, height) = (word(0), word(8).max(word(16)) as usize);
let mut planes = Vec::new();
if got >= 24 && (1..=4).contains(&total) && (1..=16_384).contains(&height) {
let span = (24 + total as usize * 5 * 24).min(got);
let mut at = 24;
while at + 16 <= span {
let pointer = u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap_or_default()) as usize;
let pitch = word(at + 12) as usize;
if pointer > 0x10000 && pointer < 1 << 40 && (16..=65_536).contains(&pitch) {
planes.push((pointer, pitch * height));
}
at += 8;
}
planes.sort_unstable();
planes.dedup();
}
static SHOWN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let words: Vec<String> = if SHOWN.fetch_add(1, Ordering::Relaxed) < 4 {
bytes[..got.min(bytes.len())].chunks(8).map(|c| format!("{:016x}", u64::from_le_bytes(c.try_into().unwrap_or_default()))).collect()
} else {
Vec::new()
};
tracing::info!(
movie = format_args!("{:#x}", movie as usize),
total,
height,
planes = planes.len(),
bytes = %words.join(" "),
"Bink frame buffers registered"
);
PLANES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new).insert(movie as usize, planes);
}
let address = REGISTER.load(Ordering::Acquire);
let original: Export = unsafe { std::mem::transmute::<usize, Export>(address) };
original(movie, buffers, b, c)
}
fn frame_decoded(movie: *mut Movie) {
let planes = PLANES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|p| p.get(&(movie as usize)).cloned());
for (at, len) in planes.unwrap_or_default() {
eonacat_xsbox_gpu::bink_frame_written(at, len);
}
}
fn movies() -> std::sync::MutexGuard<'static, Option<HashMap<usize, bool>>> {
MOVIES.lock().unwrap_or_else(|e| e.into_inner())
}
fn plausible(m: &Movie) -> bool {
(1..=16_384).contains(&m.width)
&& (1..=16_384).contains(&m.height)
&& (1..=10_000_000).contains(&m.frames)
&& m.frame_rate > 0
&& m.frame_rate_div > 0
}
fn decide(mode: u8, looping: bool, world: bool) -> bool {
match mode {
m if m == Mode::NotLooping as u8 => !looping,
m if m == Mode::All as u8 => true,
m if m == Mode::Intro as u8 => !looping && !world,
_ => false,
}
}
fn skipped(movie: *mut Movie) -> bool {
if movie.is_null() {
return false;
}
let mode = MODE.load(Ordering::Relaxed);
let mut first = false;
let skip = {
let mut movies = movies();
let movies = movies.get_or_insert_with(HashMap::new);
*movies.entry(movie as usize).or_insert_with(|| {
let m = unsafe { &*movie };
let looping = m.open_flags & WILL_LOOP != 0;
eonacat_xsbox_gpu::streamline::bink_movie_opened();
if !plausible(m) {
tracing::warn!(
width = m.width,
height = m.height,
frames = m.frames,
"a Bink movie whose structure is not the one known here (another Bink version?): not skipped"
);
return false;
}
let skip = decide(mode, looping, eonacat_xsbox_gpu::world_since().is_some());
tracing::info!(width = m.width, height = m.height, frames = m.frames, looping, skip, "Bink movie");
first = skip;
skip
})
};
if first && ORIGINALS[PAUSE].load(Ordering::Acquire) != 0 {
forward(PAUSE, movie, 1, 0, 0);
}
if skip {
unsafe {
let frames = (*movie).frames;
(*movie).frame_num = frames;
(*movie).last_frame_num = frames;
}
eonacat_xsbox_gpu::streamline::note_bink_movie();
}
skip
}
extern "system" fn close(movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
if movies()
.as_mut()
.is_some_and(|movies| movies.remove(&(movie as usize)).is_some())
{
eonacat_xsbox_gpu::streamline::bink_movie_closed();
}
forward(CLOSE, movie, a, b, c)
}
macro_rules! wrapper {
($name:ident, $i:literal, $skipped:expr) => {
extern "system" fn $name(movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
if skipped(movie) {
return $skipped;
}
eonacat_xsbox_gpu::streamline::note_bink_movie();
forward($i, movie, a, b, c)
}
};
}
macro_rules! decoding_wrapper {
($name:ident, $i:literal, $skipped:expr, $done:expr) => {
extern "system" fn $name(movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
if skipped(movie) {
return $skipped;
}
eonacat_xsbox_gpu::streamline::note_bink_movie();
let got = forward($i, movie, a, b, c);
if ($done)(got) {
frame_decoded(movie);
}
got
}
};
}
wrapper!(wait, 1, 0);
wrapper!(should_skip, 2, 0);
decoding_wrapper!(do_frame, 3, 0, |_| true);
wrapper!(do_frame_async, 4, 1);
wrapper!(do_frame_async_multi, 5, 1);
decoding_wrapper!(do_frame_async_wait, 6, 1, |done| done != 0);
wrapper!(next_frame, 7, 0);
wrapper!(goto, 8, 0);
type Copy = extern "system" fn(*mut Movie, usize, usize, usize, usize, usize, usize, usize, usize, usize, usize) -> usize;
macro_rules! copy_wrapper {
($name:ident, $i:literal) => {
#[allow(clippy::too_many_arguments)]
extern "system" fn $name(
movie: *mut Movie,
a: usize,
b: usize,
c: usize,
d: usize,
e: usize,
f: usize,
g: usize,
h: usize,
i: usize,
j: usize,
) -> usize {
if skipped(movie) {
return 0;
}
let address = ORIGINALS[$i].load(Ordering::Acquire);
let original: Copy = unsafe { std::mem::transmute::<usize, Copy>(address) };
timed($i, || original(movie, a, b, c, d, e, f, g, h, i, j))
}
};
}
copy_wrapper!(copy_to_buffer, 10);
copy_wrapper!(copy_to_buffer_rect, 11);
extern "system" fn pause(movie: *mut Movie, a: usize, b: usize, c: usize) -> usize {
if skipped(movie) {
return forward(PAUSE, movie, 1, b, c);
}
forward(PAUSE, movie, a, b, c)
}
pub struct SkipMovies<'a> {
pub inner: &'a dyn ImportResolver,
}
impl ImportResolver for SkipMovies<'_> {
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
match (self.inner.resolve(dll, symbol), symbol) {
(
Resolution::Found {
address,
provenance: Provenance::Title,
},
ImportSymbol::Name { name, .. },
) => Resolution::Found {
address: wrap(dll, name, address),
provenance: Provenance::Title,
},
(found, _) => found,
}
}
}
+212
View File
@@ -0,0 +1,212 @@
use std::ffi::c_void;
use std::sync::atomic::{AtomicU32, Ordering};
use eonacat_xsbox_gpu::device;
use eonacat_xsbox_gpu::object::{HRESULT, Iid, Object, guid};
use crate::hle::{HleExport, HleModule};
fn prepare_device() {
eonacat_xsbox_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree);
eonacat_xsbox_gpu::resource::use_page_mapper(super::xmem::map_alias);
eonacat_xsbox_gpu::resource::use_many_page_mapper(super::xmem::map_aliases);
#[cfg(windows)]
eonacat_xsbox_gpu::on_failure(host_gpu_failed);
}
extern "system" fn create_device(
adapter: *const c_void,
parameters: *const u32,
iid: *const Iid,
out: *mut *const Object,
) -> HRESULT {
prepare_device();
device::create(adapter, parameters, iid, out)
}
extern "system" fn create_device_with_level(
adapter: *const c_void,
minimum: u32,
iid: *const Iid,
out: *mut *const Object,
) -> HRESULT {
prepare_device();
device::create_with_level(adapter, minimum, iid, out)
}
const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
const S_OK: HRESULT = 0;
extern "system" fn get_debug_interface(iid: *const Iid, out: *mut *mut c_void) -> HRESULT {
if !out.is_null() {
unsafe { out.write(std::ptr::null_mut()) };
}
let iid = unsafe { iid.as_ref() }.map(eonacat_xsbox_gpu::object::guid_text);
tracing::info!(?iid, "D3D12GetDebugInterface: no debug layer");
E_NOINTERFACE
}
static DEBUG_FLAGS: AtomicU32 = AtomicU32::new(0);
extern "system" fn set_process_debug_flags(flags: u32) -> HRESULT {
DEBUG_FLAGS.store(flags, Ordering::Relaxed);
if flags != 0 {
tracing::warn!(
flags = format_args!("{flags:#x}"),
"D3D12 process debug flags kept but not acted on (no debug layer)"
);
}
S_OK
}
extern "system" fn get_process_debug_flags() -> u32 {
DEBUG_FLAGS.load(Ordering::Relaxed)
}
extern "system" fn unload_driver_module() {}
extern "system" fn flush_entire_cpu_cache() {
std::sync::atomic::fence(Ordering::SeqCst);
}
static DATA_IDS: [(&str, Iid); 31] = [
("IID_ID3D12CommandAllocator", guid(0x6102dee4, 0xaf59, 0x4b09, [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24])),
("IID_ID3D12CommandList", guid(0x7116d91c, 0xe7e4, 0x47ce, [0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5])),
("IID_ID3D12CommandQueue", guid(0x0ec870a6, 0x5d7e, 0x4c22, [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed])),
("IID_ID3D12Debug", guid(0x344488b7, 0x6846, 0x474b, [0xb9, 0x89, 0xf0, 0x27, 0x44, 0x82, 0x45, 0xe0])),
("IID_ID3D12DescriptorHeap", guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51])),
("IID_ID3D12DeviceChild", guid(0x905db94b, 0xa00c, 0x4140, [0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57])),
("IID_ID3D12Fence", guid(0x0a753dcf, 0xc4d8, 0x4b91, [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76])),
("IID_ID3D12GraphicsCommandList", guid(0x5b160d0f, 0xac1b, 0x4185, [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55])),
("IID_ID3D12Heap", guid(0x6b3b2502, 0x6e51, 0x45b3, [0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3])),
("IID_ID3D12Object", guid(0xc4fec28f, 0x7966, 0x4e95, [0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8])),
("IID_ID3D12Pageable", guid(0x63ee58fb, 0x1268, 0x4835, [0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6])),
("IID_ID3D12PipelineState", guid(0x765a30f3, 0xf624, 0x4c6f, [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45])),
("IID_ID3D12Resource", guid(0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad])),
("IID_ID3D12RootSignature", guid(0xc54a6b66, 0x72df, 0x4ee8, [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14])),
("IID_ID3D12RootSignatureDeserializer", guid(0x34ab647b, 0x3cc8, 0x46ac, [0x84, 0x1b, 0xc0, 0x96, 0x56, 0x45, 0xc0, 0x46])),
("IID_ID3D12XboxDmaCommandList", guid(0x30bc77b9, 0x8379, 0x4b25, [0x95, 0xde, 0xb8, 0x58, 0x8c, 0x42, 0x27, 0x5d])),
("IID_IDXGIAdapter", guid(0x2411e7e1, 0x12ac, 0x4ccf, [0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0])),
("IID_IDXGIAdapter1", guid(0x29038f61, 0x3839, 0x4626, [0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05])),
("IID_IDXGIAdapter2", guid(0x0aa1ae0a, 0xfa0e, 0x4b84, [0x86, 0x44, 0xe0, 0x5f, 0xf8, 0xe5, 0xac, 0xb5])),
("IID_IDXGIDevice", guid(0x54ec77fa, 0x1377, 0x44e6, [0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c])),
("IID_IDXGIDevice1", guid(0x77db970f, 0x6276, 0x48ba, [0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c])),
("IID_IDXGIDevice2", guid(0x05008617, 0xfbfd, 0x4051, [0xa7, 0x90, 0x14, 0x48, 0x84, 0xb4, 0xf6, 0xa9])),
("IID_IDXGIDeviceSubObject", guid(0x3d3e0379, 0xf9de, 0x4d58, [0xbb, 0x6c, 0x18, 0xd6, 0x29, 0x92, 0xf1, 0xa6])),
("IID_IDXGIFactory", guid(0x7b7166ec, 0x21c7, 0x44ae, [0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, 0x69])),
("IID_IDXGIFactory1", guid(0x770aae78, 0xf26f, 0x4dba, [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87])),
("IID_IDXGIFactory2", guid(0x50c83a1c, 0xe072, 0x4c48, [0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0])),
("IID_IDXGIObject", guid(0xaec22fb8, 0x76f3, 0x4639, [0x9b, 0xe0, 0x28, 0xeb, 0x43, 0xa6, 0x7a, 0x2e])),
("IID_IDXGISwapChain", guid(0x310d36a0, 0xd2e7, 0x4c0a, [0xaa, 0x04, 0x6a, 0x9d, 0x23, 0xb8, 0x88, 0x6a])),
("IID_IDXGISwapChain1", guid(0x790a45f7, 0x0d42, 0x4876, [0x98, 0x3a, 0x0a, 0x55, 0xcf, 0xe6, 0xf4, 0xaa])),
("IID_IGraphicsUnknown", guid(0xaceeea63, 0xe0a9, 0x4a1c, [0xbb, 0xec, 0x71, 0xb2, 0xf4, 0x85, 0xf7, 0x58])),
("WKPDID_D3DDebugObjectNameW", guid(0x4cca5fd8, 0x921f, 0x42c8, [0x85, 0x66, 0x70, 0xca, 0xf2, 0xa9, 0xb7, 0x41])),
];
#[cfg(windows)]
fn host_gpu_failed(what: &str) -> ! {
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
eonacat_xsbox_gpu::loader::log_crash(&format!("eonacat-xs: host GPU failure: {what}"));
eonacat_xsbox_gpu::core::logging::flush(std::time::Duration::from_secs(2));
const DXGI_ERROR_DEVICE_REMOVED: u32 = 0x887A_0005;
unsafe { TerminateProcess(GetCurrentProcess(), DXGI_ERROR_DEVICE_REMOVED) };
unreachable!("the process has ended")
}
pub fn precompile(container: &[u8]) -> Result<bool, String> {
#[cfg(windows)]
{
eonacat_xsbox_gpu::shader_cache::precompile(container)
}
#[cfg(not(windows))]
{
let _ = container;
Err("no host".into())
}
}
pub fn warm_shader(container: &[u8]) -> Result<bool, String> {
#[cfg(windows)]
{
eonacat_xsbox_gpu::shader_cache::precompile(container).map(|was_there| !was_there)
}
#[cfg(not(windows))]
{
let _ = container;
Err("no shader cache on this host".into())
}
}
pub fn shader_translator_id() -> Option<String> {
#[cfg(windows)]
{
Some(eonacat_xsbox_gpu::shader_cache::translator_id())
}
#[cfg(not(windows))]
{
None
}
}
pub fn use_shader_cache(dir: std::path::PathBuf) {
#[cfg(windows)]
{
eonacat_xsbox_gpu::pipeline::use_pipeline_cache(dir.with_file_name("pipelines"));
eonacat_xsbox_gpu::shader_cache::use_shader_cache(dir);
}
#[cfg(not(windows))]
let _ = dir;
}
pub(crate) fn module() -> HleModule {
let function = |name, address: *const ()| HleExport {
name,
address: address as usize,
};
let mut exports = vec![
function("D3D12ConfigureVirtualMemoryX", device::configure_virtual_memory as *const ()),
function("D3D12XboxCreateDevice", create_device as *const ()),
function("D3D12CreateDevice", create_device_with_level as *const ()),
function("D3D12SerializeRootSignature", eonacat_xsbox_gpu::root::serialize as *const ()),
function(
"D3D12SerializeVersionedRootSignature",
eonacat_xsbox_gpu::root::serialize_versioned as *const (),
),
function(
"D3D12CreateRootSignatureDeserializer",
eonacat_xsbox_gpu::root::create_deserializer as *const (),
),
function(
"D3D12CreateVersionedRootSignatureDeserializer",
eonacat_xsbox_gpu::root::create_versioned_deserializer as *const (),
),
function("D3D10CreateBlob", eonacat_xsbox_gpu::root::create_blob as *const ()),
function("D3D12GetDebugInterface", get_debug_interface as *const ()),
function("D3D12XboxSetProcessDebugFlags", set_process_debug_flags as *const ()),
function("D3D12XboxGetProcessDebugFlags", get_process_debug_flags as *const ()),
function("D3D12XboxUnloadDriverModule", unload_driver_module as *const ()),
function("D3DFlushEntireCpuCache", flush_entire_cpu_cache as *const ()),
HleExport {
name: "IID_ID3D12Device",
address: (&raw const device::IID) as usize,
},
];
exports.extend(DATA_IDS.iter().map(|(name, id)| HleExport {
name,
address: (id as *const Iid) as usize,
}));
HleModule {
name: "d3d12x",
dlls: &["d3d12_xs.dll"],
exports,
}
}
+233
View File
@@ -0,0 +1,233 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put, text,
with_spare,
};
pub const HDR_PROVIDER: Guid = Guid::new(
0x03f0_fe74,
0xfdd9,
0x4e5c,
[0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5],
);
pub const HDR_IID: Guid = Guid::new(
0x35f0_7670,
0x706e,
0x4bfb,
[0x94, 0x76, 0x09, 0x07, 0x98, 0xc5, 0xeb, 0xf3],
);
pub const SHELL: Guid = Guid::new(
0x1b33_9674,
0x328d,
0x4283,
[0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39],
);
pub const CAPTURE_PROVIDER: Guid = Guid::new(
0xa4f1_aee2,
0x4bf1,
0x4485,
[0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27],
);
pub const CAPTURE_IID_2026: Guid = Guid::new(
0x22e6_72d7,
0xb4e3,
0x406c,
[0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e],
);
pub static HDR_OBJECT: Object = Object::new("hdr", &HDR_VTABLE);
pub static SHELL_OBJECT: Object = Object::new("shell", &SHELL_VTABLE);
pub static CAPTURE_OBJECT: Object = Object::new("capture", &CAPTURE_VTABLE);
pub const INTERFACES: &[Interface] = &[
(HDR_PROVIDER, HDR_IID, &HDR_OBJECT),
(SHELL, SHELL, &SHELL_OBJECT),
(CAPTURE_PROVIDER, CAPTURE_IID_2026, &CAPTURE_OBJECT),
];
type This = *const Object;
extern "system" fn try_enable_hdr(_: This, preference: u32, info: *mut HdrModeInfo) -> u32 {
tracing::info!(preference, "HDR mode: disabled (SDR presentation)");
if !info.is_null() {
unsafe {
info.write(HdrModeInfo {
min_tone_map_luminance: 0.0,
max_tone_map_luminance: 100.0,
max_full_frame_tone_map_luminance: 100.0,
});
}
}
2
}
#[repr(C)]
pub struct HdrModeInfo {
min_tone_map_luminance: f32,
max_tone_map_luminance: f32,
max_full_frame_tone_map_luminance: f32,
}
extern "system" fn launch_uri(_: This, _user: *const c_void, uri: *const c_char) -> HRESULT {
tracing::info!(uri = text(uri).unwrap_or_default(), "URI not launched");
NOT_SUPPORTED
}
#[cfg(windows)]
extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT {
use windows_sys::Win32::System::Power::{
PowerCreateRequest, PowerRequestDisplayRequired, PowerSetRequest,
};
use windows_sys::Win32::System::Threading::{
POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT,
};
if out.is_null() {
return super::xasync::E_INVALIDARG;
}
let mut reason: Vec<u16> = "Title display deferral\0".encode_utf16().collect();
let mut context = REASON_CONTEXT {
Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
..Default::default()
};
context.Reason.SimpleReasonString = reason.as_mut_ptr();
let request = unsafe { PowerCreateRequest(&context) };
if request as isize == -1 {
return last_error();
}
if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 {
let hr = last_error();
unsafe { windows_sys::Win32::Foundation::CloseHandle(request) };
return hr;
}
put(out, request)
}
#[cfg(windows)]
extern "system" fn close_deferral(_: This, handle: *mut c_void) {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Power::{PowerClearRequest, PowerRequestDisplayRequired};
if !handle.is_null() {
unsafe {
PowerClearRequest(handle, PowerRequestDisplayRequired);
CloseHandle(handle);
}
}
}
#[cfg(windows)]
fn last_error() -> HRESULT {
let code = unsafe { windows_sys::Win32::Foundation::GetLastError() };
(0x8007_0000 | (code & 0xffff)) as i32
}
#[repr(C)]
pub struct ScreenshotResult {
pub local_id: [u8; 250],
pub formats: u16,
}
const SDR: u16 = 1;
#[cfg(windows)]
extern "system" fn take_screenshot(
_: This,
_user: *const c_void,
result: *mut ScreenshotResult,
) -> HRESULT {
use std::sync::atomic::{AtomicU32, Ordering};
static TAKEN: AtomicU32 = AtomicU32::new(0);
if result.is_null() {
return super::xasync::E_INVALIDARG;
}
let seconds = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let name = format!(
"photo-{seconds}-{}.png",
TAKEN.fetch_add(1, Ordering::Relaxed)
);
let path = crate::hle::runtime::title().screenshots().join(&name);
tracing::info!(path = %path.display(), "screenshot asked for: the next frame shown");
eonacat_xsbox_gpu::screenshot::request(path);
let mut out = ScreenshotResult {
local_id: [0; 250],
formats: SDR,
};
out.local_id[..name.len()].copy_from_slice(name.as_bytes());
unsafe { result.write(out) };
S_OK
}
#[cfg(not(windows))]
extern "system" fn take_screenshot(
_: This,
_user: *const c_void,
_result: *mut ScreenshotResult,
) -> HRESULT {
tracing::info!("screenshot not taken");
NOT_SUPPORTED
}
static HDR_VTABLE: Methods<13> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (),
try_enable_hdr as *const (),
]);
#[cfg(windows)]
static SHELL_VTABLE: Methods<14> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
launch_uri as *const (),
acquire_deferral as *const (),
close_deferral as *const (),
]);
#[cfg(not(windows))]
static SHELL_VTABLE: Methods<14> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
launch_uri as *const (),
missing::<4> as *const (),
missing::<5> as *const (),
]);
static CAPTURE_VTABLE: Methods<26> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (),
missing::<4> as *const (),
take_screenshot as *const (),
missing::<6> as *const (),
missing::<7> as *const (),
missing::<8> as *const (),
missing::<9> as *const (),
missing::<10> as *const (),
missing::<11> as *const (),
missing::<12> as *const (),
missing::<13> as *const (),
missing::<14> as *const (),
missing::<15> as *const (),
missing::<16> as *const (),
missing::<17> as *const (),
]);
+288
View File
@@ -0,0 +1,288 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::c_void;
use std::sync::Mutex;
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{HRESULT, S_OK};
use crate::hle::{HleModule};
use crate::hle_export;
mod convolve;
fn convolve_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("EONACAT_XS_DSP_CONVOLVE").is_none_or(|v| v != "0"))
}
const GAIN: f32 = 2.0;
fn gain() -> f32 {
static GAIN_SET: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
*GAIN_SET.get_or_init(|| {
std::env::var("EONACAT_XS_DSP_GAIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(GAIN)
})
}
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
const CONVOLUTION: u32 = 1;
const STEREO_OPTIONS: u32 = 2 | 8;
const NOT_FOR_CONVOLUTION: u32 = 4;
pub struct Dsp {
max_streams: u32,
active: Mutex<u32>,
}
#[repr(C, packed)]
pub struct StreamDesc {
kind: u32,
options: u32,
frames: u32,
channels: u32,
ir_floats: u32,
ir: *const f32,
}
#[repr(C)]
pub struct Status {
submitted: AtomicU32,
completed: AtomicU32,
reserved: AtomicU32,
result: AtomicI32,
}
const _: () = {
assert!(size_of::<Status>() == 16);
assert!(align_of::<Status>() == 4);
assert!(std::mem::offset_of!(Status, submitted) == 0);
assert!(std::mem::offset_of!(Status, completed) == 4);
assert!(std::mem::offset_of!(Status, reserved) == 8);
assert!(std::mem::offset_of!(Status, result) == 12);
};
struct SubmitState {
last: u32,
convolver: Option<convolve::Convolver>,
}
pub struct Stream {
dsp: *mut Dsp,
frames: u32,
channels: u32,
submit: Mutex<SubmitState>,
status: Box<Status>,
}
#[repr(C)]
pub struct Command {
gains: [f32; 2],
input: *const f32,
output: *mut f32,
reserved: u64,
}
pub extern "system" fn XDspConnectWithMaximumStreamLimit(
base: *mut c_void,
base_length: u32,
ir_seconds: u32,
max_streams: u32,
max_channels: u32,
out: *mut *mut Dsp,
) -> HRESULT {
if base.is_null()
|| !(0x1_0000..=0x1F40_0000).contains(&base_length)
|| ir_seconds > 0x80
|| max_streams > 0x100
|| max_channels > 2
{
return E_INVALIDARG;
}
if out.is_null() {
return E_POINTER;
}
tracing::info!(
base_length,
ir_seconds,
max_streams,
max_channels,
"audio DSP connected"
);
let dsp = Box::new(Dsp {
max_streams,
active: Mutex::new(0),
});
unsafe { out.write(Box::into_raw(dsp)) };
S_OK
}
pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT {
if dsp.is_null() {
return E_INVALIDARG;
}
drop(unsafe { Box::from_raw(dsp) });
S_OK
}
fn valid(desc: &StreamDesc) -> bool {
let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
let shape = if kind == CONVOLUTION {
(1..=2).contains(&channels)
&& matches!(frames, 0x200 | 0x400)
&& options & NOT_FOR_CONVOLUTION == 0
} else {
channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800)
};
shape && (options & STEREO_OPTIONS == 0 || channels == 2)
}
pub extern "system" fn XDspActivate(
dsp: *mut Dsp,
desc: *const StreamDesc,
status: *mut *const Status,
stream: *mut *mut Stream,
) -> HRESULT {
if status.is_null() || stream.is_null() {
return E_POINTER;
}
if dsp.is_null() || desc.is_null() {
return E_INVALIDARG;
}
let desc = unsafe { &*desc };
if !valid(desc) {
return E_INVALIDARG;
}
let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
let (ir, ir_floats) = (desc.ir, desc.ir_floats);
let convolver = if convolve_on() && kind == CONVOLUTION && channels == 1 && frames == 0x400 && !ir.is_null() {
convolve::Convolver::new(unsafe { std::slice::from_raw_parts(ir, ir_floats as usize) })
} else {
None
};
tracing::debug!(
kind,
options,
frames,
channels,
ir_floats,
computed = convolver.is_some(),
"audio DSP stream activated"
);
{
let dsp = unsafe { &*dsp };
let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner());
if *active >= dsp.max_streams {
return E_OUTOFMEMORY;
}
*active += 1;
}
let new = Box::new(Stream {
dsp,
frames: desc.frames,
channels: desc.channels,
submit: Mutex::new(SubmitState { last: 0, convolver }),
status: Box::new(Status {
submitted: AtomicU32::new(0),
completed: AtomicU32::new(0),
reserved: AtomicU32::new(0),
result: AtomicI32::new(S_OK),
}),
});
let raw = Box::into_raw(new);
unsafe {
status.write(std::ptr::from_ref(&*(*raw).status));
stream.write(raw);
}
S_OK
}
pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT {
if stream.is_null() {
return E_INVALIDARG;
}
let stream = unsafe { Box::from_raw(stream) };
let dsp = unsafe { &*stream.dsp };
*dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
S_OK
}
fn ramp(output: &mut [f32], frames: u32, channels: u32, [begin, end]: [f32; 2]) {
if (begin, end) == (1.0, 1.0) || frames == 0 {
return;
}
let step = (end - begin) / frames as f32;
let channels = channels.max(1) as usize;
for (i, frame) in output.chunks_mut(channels).enumerate() {
let scale = begin + i as f32 * step;
frame.iter_mut().for_each(|s| *s *= scale);
}
}
pub extern "system" fn XDspSubmitCommand(
stream: *mut Stream,
command: *const Command,
ticket: *mut u32,
) -> HRESULT {
if stream.is_null() || command.is_null() {
return E_INVALIDARG;
}
let (stream, command) = unsafe { (&*stream, &*command) };
let mut submit = stream.submit.lock().unwrap_or_else(|e| e.into_inner());
let next = submit.last.wrapping_add(1);
submit.last = next;
stream.status.submitted.store(next, Ordering::Release);
let samples = (stream.frames * stream.channels) as usize;
if !command.output.is_null() && !command.input.is_null() && let Some(convolver) = submit.convolver.as_mut() {
let (input, output) = unsafe {
(std::slice::from_raw_parts(command.input, samples), std::slice::from_raw_parts_mut(command.output, samples))
};
convolver.process(input, output, gain());
ramp(output, stream.frames, stream.channels, command.gains);
} else if !command.output.is_null() {
unsafe { std::ptr::write_bytes(command.output, 0, samples) };
}
stream.status.result.store(S_OK, Ordering::Relaxed);
stream.status.completed.store(next, Ordering::Release);
drop(submit);
if !ticket.is_null() {
unsafe { ticket.write(next) };
}
S_OK
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "dsp",
dlls: &["chad.dll"],
exports: vec![
hle_export!(XDspConnectWithMaximumStreamLimit),
hle_export!(XDspDisconnect),
hle_export!(XDspActivate),
hle_export!(XDspDeactivate),
hle_export!(XDspSubmitCommand),
],
}
}
@@ -0,0 +1,157 @@
const N: usize = 2048;
const B: usize = 1024;
const TRAILER: u32 = 0xFFFF_ACE1;
struct Fft {
cos: Vec<f32>,
sin: Vec<f32>,
rev: Vec<u16>,
}
fn fft() -> &'static Fft {
static FFT: std::sync::OnceLock<Fft> = std::sync::OnceLock::new();
FFT.get_or_init(|| {
let bits = N.trailing_zeros();
let rev = (0..N).map(|i| (i.reverse_bits() >> (usize::BITS - bits)) as u16).collect();
let (cos, sin) = (0..N / 2)
.map(|k| {
let a = -2.0 * std::f64::consts::PI * k as f64 / N as f64;
(a.cos() as f32, a.sin() as f32)
})
.unzip();
Fft { cos, sin, rev }
})
}
impl Fft {
fn run(&self, re: &mut [f32; N], im: &mut [f32; N], inverse: bool) {
for i in 0..N {
let j = self.rev[i] as usize;
if i < j {
re.swap(i, j);
im.swap(i, j);
}
}
let sign = if inverse { -1.0 } else { 1.0 };
let mut len = 2;
while len <= N {
let half = len / 2;
let step = N / len;
for start in (0..N).step_by(len) {
for k in 0..half {
let (wr, wi) = (self.cos[k * step], sign * self.sin[k * step]);
let (a, b) = (start + k, start + k + half);
let (br, bi) = (re[b] * wr - im[b] * wi, re[b] * wi + im[b] * wr);
re[b] = re[a] - br;
im[b] = im[a] - bi;
re[a] += br;
im[a] += bi;
}
}
len *= 2;
}
}
}
pub(super) struct Convolver {
h_re: Vec<f32>,
h_im: Vec<f32>,
parts: usize,
x_re: Vec<f32>,
x_im: Vec<f32>,
head: usize,
quiet: usize,
}
impl Convolver {
pub(super) fn new(ir: &[f32]) -> Option<Self> {
if ir.is_empty() || !ir.len().is_multiple_of(N) {
return None;
}
let mut blocks = ir.len() / N;
if ir[(blocks - 1) * N].to_bits() == TRAILER {
blocks -= 1;
}
while blocks > 0 && ir[(blocks - 1) * N..blocks * N].iter().all(|&v| v == 0.0) {
blocks -= 1;
}
let parts = blocks.max(1);
let mut h_re = vec![0f32; parts * B];
let mut h_im = vec![0f32; parts * B];
for k in 0..blocks {
let block = &ir[k * N..(k + 1) * N];
for bin in 0..B {
let (r, i) = (block[2 * bin], block[2 * bin + 1]);
h_re[k * B + bin] = if r.is_finite() { r } else { 0.0 };
h_im[k * B + bin] = if i.is_finite() { i } else { 0.0 };
}
}
Some(Self {
h_re,
h_im,
parts,
x_re: vec![0f32; parts * B],
x_im: vec![0f32; parts * B],
head: 0,
quiet: usize::MAX,
})
}
pub(super) fn process(&mut self, input: &[f32], output: &mut [f32], gain: f32) {
let silent = input.iter().all(|&v| v == 0.0 || !v.is_finite());
self.quiet = if silent { self.quiet.saturating_add(1) } else { 0 };
self.head = (self.head + 1) % self.parts;
let slot = self.head * B;
if silent {
self.x_re[slot..slot + B].fill(0.0);
self.x_im[slot..slot + B].fill(0.0);
if self.quiet >= self.parts {
output.fill(0.0);
return;
}
} else {
let mut re = [0f32; N];
let mut im = [0f32; N];
for (r, &v) in re.iter_mut().zip(input) {
*r = if v.is_finite() { v } else { 0.0 };
}
fft().run(&mut re, &mut im, false);
self.x_re[slot..slot + B].copy_from_slice(&re[..B]);
self.x_im[slot..slot + B].copy_from_slice(&im[..B]);
}
let mut yr = [0f32; N];
let mut yi = [0f32; N];
for k in 0..self.parts {
let x = ((self.head + self.parts - k) % self.parts) * B;
let h = k * B;
let (xr, xi) = (&self.x_re[x..x + B], &self.x_im[x..x + B]);
let (hr, hi) = (&self.h_re[h..h + B], &self.h_im[h..h + B]);
for bin in 0..B {
yr[bin] += xr[bin] * hr[bin] - xi[bin] * hi[bin];
yi[bin] += xr[bin] * hi[bin] + xi[bin] * hr[bin];
}
}
for bin in 1..B {
yr[N - bin] = yr[bin];
yi[N - bin] = -yi[bin];
}
yi[0] = 0.0;
fft().run(&mut yr, &mut yi, true);
let scale = gain / N as f32;
for (o, &v) in output.iter_mut().zip(&yr[B..]) {
*o = v * scale;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,61 @@
use std::{ffi::{c_char, c_void}, fs::File, os::windows::{ffi::OsStrExt, io::AsRawHandle}, sync::OnceLock};
type Open = unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> i32;
type Read = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u64) -> i32;
type Close = unsafe extern "system" fn(*mut c_void);
type Limits = unsafe extern "system" fn(*mut u32, *mut u32, *mut u64);
struct Api { open: Open, read: Read, close: Close, limits: Option<Limits> }
#[link(name="kernel32")]
unsafe extern "system" {
fn LoadLibraryExW(path: *const u16, file: *mut c_void, flags: u32) -> *mut c_void;
fn GetProcAddress(module: *mut c_void, name: *const c_char) -> *const c_void;
}
fn api() -> Option<&'static Api> {
static API: OnceLock<Option<Api>> = OnceLock::new();
API.get_or_init(|| {
let path = std::env::current_exe().ok()?.parent()?.join("eonacat-xs-dstorage-bridge.dll");
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let lib = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0x100 | 0x1000) };
if lib.is_null() { return None; }
let open = unsafe { GetProcAddress(lib, c"eonacat_xs_ds_open".as_ptr()) };
let read = unsafe { GetProcAddress(lib, c"eonacat_xs_ds_read".as_ptr()) };
let close = unsafe { GetProcAddress(lib, c"eonacat_xs_ds_close".as_ptr()) };
if open.is_null() || read.is_null() || close.is_null() { return None; }
let limits = unsafe { GetProcAddress(lib, c"eonacat_xs_ds_get_limits".as_ptr()) };
Some(Api {
open: unsafe { std::mem::transmute::<*const c_void, Open>(open) },
read: unsafe { std::mem::transmute::<*const c_void, Read>(read) },
close: unsafe { std::mem::transmute::<*const c_void, Close>(close) },
limits: if limits.is_null() { None } else { Some(unsafe { std::mem::transmute::<*const c_void, Limits>(limits) }) },
})
}).as_ref()
}
pub(super) struct NativeFile { context: *mut c_void, api: &'static Api }
unsafe impl Send for NativeFile {}
unsafe impl Sync for NativeFile {}
impl NativeFile {
pub(super) fn open(file: &File) -> Option<Self> {
let api=api()?; let mut context=std::ptr::null_mut();
let result=unsafe { (api.open)(file.as_raw_handle().cast(), &mut context) };
(result >= 0 && !context.is_null()).then_some(Self { context, api })
}
pub(super) fn limits(&self) -> Option<(u32, u32, u64)> {
let limits = self.api.limits?;
let (mut slots, mut wait_ms, mut staging_bytes) = (0, 0, 0);
unsafe { limits(&mut slots, &mut wait_ms, &mut staging_bytes) };
Some((slots, wait_ms, staging_bytes))
}
pub(super) fn read(&self, output: &mut [u8], offset: u64) -> Result<usize,i32> {
let len=u32::try_from(output.len()).map_err(|_| -1)?;
let hr=unsafe { (self.api.read)(self.context, output.as_mut_ptr().cast(), len, offset) };
if hr < 0 { Err(hr) } else { Ok(output.len()) }
}
}
impl Drop for NativeFile { fn drop(&mut self) { unsafe { (self.api.close)(self.context) } } }
+392
View File
@@ -0,0 +1,392 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use eonacat_xsbox_gpu::object::Object;
use eonacat_xsbox_gpu::streamline::{self, Taken, Upscale, plan::Camera};
use eonacat_xsbox_gpu::loader::{ImportResolver, Provenance, Resolution};
use eonacat_xsbox_gpu::pe::ImportSymbol;
pub const LOADER_DLL: &str = "amd_fidelityfx_loader_xbox.dll";
const OK: u32 = 0;
const PARAMETER: u32 = 6;
const CREATE_UPSCALE: u64 = 0x1_0000;
const DISPATCH_UPSCALE: u64 = 0x1_0001;
pub fn init_pc(dir: &std::path::Path) -> bool {
match pc::init(dir) {
Ok(()) => true,
Err(error) => {
tracing::warn!(%error, "PC FidelityFX is unavailable; retaining the title renderer");
false
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct Header {
kind: u64,
next: *mut Header,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct CreateUpscale {
header: Header,
flags: u32,
max_render: [u32; 2],
max_output: [u32; 2],
message: usize,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct Resource {
resource: *mut c_void,
description: [u32; 8],
state: u32,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct DispatchUpscale {
header: Header,
list: *mut c_void,
resources: [Resource; 7],
jitter: [f32; 2],
motion_scale: [f32; 2],
render_size: [u32; 2],
upscale_size: [u32; 2],
enable_sharpening: u8,
sharpness: f32,
frame_time_delta: f32,
pre_exposure: f32,
reset: u8,
camera_near: f32,
camera_far: f32,
camera_fov_angle_vertical: f32,
view_space_to_meters_factor: f32,
flags: u32,
}
const _: () = assert!(size_of::<CreateUpscale>() == 0x30);
const _: () = assert!(size_of::<Resource>() == 0x30);
const _: () = assert!(size_of::<DispatchUpscale>() == 0x1b0);
type Create = unsafe extern "C" fn(*mut *mut c_void, *mut Header, *const c_void) -> u32;
type Destroy = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> u32;
type Call = unsafe extern "C" fn(*mut *mut c_void, *mut Header) -> u32;
static ORIGINALS: [AtomicUsize; 5] = [const { AtomicUsize::new(0) }; 5];
const NAMES: [&str; 5] = ["ffxCreateContext", "ffxDestroyContext", "ffxConfigure", "ffxQuery", "ffxDispatch"];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Created {
flags: u32,
max_render: [u32; 2],
max_output: [u32; 2],
clamped: bool,
}
static CONTEXTS: Mutex<Option<HashMap<usize, Created>>> = Mutex::new(None);
macro_rules! once {
($level:ident, $($arg:tt)*) => {{
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::$level!($($arg)*));
}};
}
mod pc;
pub struct Interpose<'a> {
pub inner: &'a dyn ImportResolver,
}
impl ImportResolver for Interpose<'_> {
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
let found = self.inner.resolve(dll, symbol);
if !dll.eq_ignore_ascii_case(LOADER_DLL) || !(streamline::serving() || pc::active()) {
return found;
}
match (&found, symbol) {
(&Resolution::Found { address, .. }, ImportSymbol::Name { name, .. }) => match interpose(name, address) {
Some(ours) => Resolution::Found { address: ours, provenance: Provenance::Hle },
None => found,
},
_ => found,
}
}
}
pub fn wrap(dll: &str, name: &str, address: usize) -> usize {
if address == 0 || !dll.eq_ignore_ascii_case(LOADER_DLL) || !streamline::serving() {
return address;
}
interpose(name, address).unwrap_or(address)
}
fn interpose(name: &str, original: usize) -> Option<usize> {
let i = NAMES.iter().position(|n| *n == name)?;
ORIGINALS[i].store(original, Relaxed);
let ours = [
ffxCreateContext as *const () as usize,
ffxDestroyContext as *const () as usize,
ffxConfigure as *const () as usize,
ffxQuery as *const () as usize,
ffxDispatch as *const () as usize,
][i];
tracing::info!(name, original = format_args!("{original:#x}"), "FidelityFX: the title's import goes through ours (DLSS / frame generation)");
Some(ours)
}
fn original(i: usize) -> Option<*const ()> {
let address = ORIGINALS[i].load(Relaxed);
(address != 0).then_some(address as *const ())
}
fn contexts<T>(f: impl FnOnce(&mut HashMap<usize, Created>) -> T) -> T {
let mut contexts = CONTEXTS.lock().unwrap_or_else(|e| e.into_inner());
f(contexts.get_or_insert_with(HashMap::new))
}
const SHIPPING_MAX_OUTPUT: [u32; 2] = [1920, 1080];
const SHIPPING_MAX_RENDER: [u32; 2] = [1280, 720];
fn shipping_sizes(render: [u32; 2], output: [u32; 2]) -> Option<([u32; 2], [u32; 2])> {
((render, output) != (SHIPPING_MAX_RENDER, SHIPPING_MAX_OUTPUT)).then_some((SHIPPING_MAX_RENDER, SHIPPING_MAX_OUTPUT))
}
fn find(desc: *mut Header, kind: u64) -> Option<*mut Header> {
let mut at = desc;
for _ in 0..16 {
if at.is_null() {
return None;
}
let header = unsafe { at.read() };
if header.kind == kind {
return Some(at);
}
at = header.next;
}
None
}
extern "C" fn ffxCreateContext(context: *mut *mut c_void, desc: *mut Header, memory: *const c_void) -> u32 {
let Some(create) = original(0) else { return PARAMETER };
let call = |desc: *mut Header| unsafe { std::mem::transmute::<*const (), Create>(create)(context, desc, memory) };
let Some(upscale) = find(desc, CREATE_UPSCALE) else {
return call(desc);
};
let asked = unsafe { upscale.cast::<CreateUpscale>().read() };
if pc::active() && !streamline::upscaling() {
return pc::create(context, asked, memory);
}
let shipping = streamline::upscaling().then(|| shipping_sizes(asked.max_render, asked.max_output)).flatten();
let clamped = shipping.is_some();
let code = if let Some((render, output)) = shipping {
let mut fitted = asked;
fitted.max_render = render;
fitted.max_output = output;
unsafe { upscale.cast::<CreateUpscale>().write(fitted) };
let code = call(desc);
unsafe { upscale.cast::<CreateUpscale>().write(asked) };
tracing::info!(
asked_render = ?asked.max_render,
asked_output = ?asked.max_output,
made_render = ?fitted.max_render,
made_output = ?fitted.max_output,
code,
"FidelityFX: the title's upscaler made at a size its shipping FSR4 accepts; DLSS upscales to the size asked"
);
code
} else {
call(desc)
};
if code != OK || context.is_null() {
if code != OK && !streamline::upscaling() {
tracing::error!(
code,
max_render = ?asked.max_render,
max_output = ?asked.max_output,
"FidelityFX: the title's own upscaler was not made at these sizes (its shipping FSR4 takes 1280x720 or 1920x1080 in, 1920x1080 out): with frame generation at another output size, set EONACAT_XS_DLSS=1 as well; the title fails at its first upscaling without an upscaler"
);
}
return code;
}
let handle = unsafe { *context } as usize;
let created = Created { flags: asked.flags, max_render: asked.max_render, max_output: asked.max_output, clamped };
tracing::info!(
context = format_args!("{handle:#x}"),
flags = format_args!("{:#x}", created.flags),
max_render = ?created.max_render,
max_output = ?created.max_output,
"FidelityFX: the title made its upscaler"
);
contexts(|c| c.insert(handle, created));
code
}
extern "C" fn ffxDestroyContext(context: *mut *mut c_void, memory: *const c_void) -> u32 {
if let Some(code) = pc::destroy(context) {
return code;
}
let Some(destroy) = original(1) else { return PARAMETER };
if !context.is_null() {
let handle = unsafe { *context } as usize;
if contexts(|c| c.remove(&handle)).is_some() {
streamline::upscaler_destroyed(handle);
}
}
unsafe { std::mem::transmute::<*const (), Destroy>(destroy)(context, memory) }
}
extern "C" fn ffxConfigure(context: *mut *mut c_void, desc: *mut Header) -> u32 {
if let Some(code) = pc::call(context, desc, false) {
return code;
}
let Some(configure) = original(2) else { return PARAMETER };
unsafe { std::mem::transmute::<*const (), Call>(configure)(context, desc) }
}
extern "C" fn ffxQuery(context: *mut *mut c_void, desc: *mut Header) -> u32 {
if let Some(code) = pc::call(context, desc, true) {
return code;
}
let Some(query) = original(3) else { return PARAMETER };
if !desc.is_null() {
let kind = unsafe { (*desc).kind };
static SEEN: Mutex<Vec<u64>> = Mutex::new(Vec::new());
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
if !seen.contains(&kind) && seen.len() < 32 {
seen.push(kind);
tracing::info!(kind = format_args!("{kind:#x}"), "FidelityFX: the title asks a query of this kind (answered by its own DLL)");
}
}
unsafe { std::mem::transmute::<*const (), Call>(query)(context, desc) }
}
extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 {
if let Some(code) = pc::dispatch(context, desc) {
return code;
}
let Some(dispatch) = original(4) else { return PARAMETER };
let own = || unsafe { std::mem::transmute::<*const (), Call>(dispatch)(context, desc) };
if context.is_null() || desc.is_null() {
return own();
}
let handle = unsafe { *context as usize };
let Some(asked) = find(desc, DISPATCH_UPSCALE) else {
return own();
};
let Some(created) = contexts(|c| c.get(&handle).copied()) else {
once!(warn, "FidelityFX: an upscale dispatch on a context we did not see made; the title's own runs");
return own();
};
let d = unsafe { asked.cast::<DispatchUpscale>().read() };
first_dispatch(&d, &created);
let up = upscale(&d, &created, handle);
match streamline::upscale(&up) {
Taken::Dlss => OK,
Taken::Noted => own(),
Taken::No(why) if created.clamped => {
refused(why);
if eonacat_xsbox_gpu::upscale_fallback::upscale(&up) {
once!(warn, "FidelityFX: DLSS did not take an upscaling on a context made smaller than asked; a plain (bilinear) one ran");
} else {
once!(warn, "FidelityFX: DLSS did not take an upscaling on a context made smaller than asked; none ran");
}
OK
}
Taken::No(why) => {
streamline::forwarded();
refused(why);
own()
}
}
}
fn refused(why: &'static str) {
static SEEN: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
if !seen.contains(&why) {
seen.push(why);
tracing::warn!("FidelityFX: the title's own upscaling runs: {why}");
}
}
fn first_dispatch(d: &DispatchUpscale, created: &Created) {
once!(
info,
render = ?d.render_size,
output = ?d.upscale_size,
max_render = ?created.max_render,
max_output = ?created.max_output,
create_flags = format_args!("{:#x}", created.flags),
flags = format_args!("{:#x}", d.flags),
jitter = ?d.jitter,
motion_vector_scale = ?d.motion_scale,
near = d.camera_near,
far = d.camera_far,
fov = d.camera_fov_angle_vertical,
frame_ms = d.frame_time_delta,
pre_exposure = d.pre_exposure,
reset = d.reset != 0,
sharpening = d.enable_sharpening != 0,
resources = ?d.resources.iter().map(|r| (r.resource as usize != 0, r.description[1], r.description[2], r.description[3], r.state)).collect::<Vec<_>>(),
"FidelityFX: the title's first upscale dispatch (resources: present, format, width, height, state)"
);
}
fn upscale(d: &DispatchUpscale, created: &Created, context: usize) -> Upscale {
let output = if d.upscale_size == [0, 0] { created.max_output } else { d.upscale_size };
Upscale {
context,
list: d.list.cast::<Object>().cast_const(),
resources: d.resources.map(|r| (r.resource.cast::<Object>().cast_const(), r.state)),
camera: Camera {
jitter: d.jitter,
motion_scale: d.motion_scale,
render: d.render_size,
output,
near: d.camera_near,
far: d.camera_far,
fov_y: d.camera_fov_angle_vertical,
reset: d.reset != 0,
flags: created.flags,
},
pre_exposure: d.pre_exposure,
frame_ms: d.frame_time_delta,
view_space_to_meters: d.view_space_to_meters_factor,
}
}
@@ -0,0 +1,307 @@
use super::*;
use std::ffi::CStr;
use std::path::Path;
use std::ptr::{null, null_mut};
use std::sync::{Arc, OnceLock};
use windows_sys::Win32::Foundation::FreeLibrary;
use windows_sys::Win32::System::LibraryLoader::{
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
};
const UPSCALER_DLL: &str = "amd_fidelityfx_upscaler_dx12.dll";
const GET_VERSIONS: u64 = 4;
const GET_PROVIDER_VERSION: u64 = 6;
const QUERY_MEMORY_USAGE: u64 = 0x1_0009;
const NO_PROVIDER: u32 = 4;
#[repr(C)]
struct Versions {
header: Header,
effect: u64,
device: *mut c_void,
count: *mut u64,
ids: *mut u64,
names: *mut *const std::ffi::c_char,
}
#[repr(C)]
struct Backend {
header: Header,
device: *mut c_void,
}
struct Module(usize);
impl Drop for Module {
fn drop(&mut self) {
unsafe { FreeLibrary(self.0 as _) };
}
}
struct Api {
_library: Module,
create: Create,
destroy: Destroy,
configure: Call,
query: Call,
dispatch: Call,
device: usize,
}
static API: OnceLock<Api> = OnceLock::new();
struct Context {
handle: Mutex<usize>,
created: Created,
}
impl Drop for Context {
fn drop(&mut self) {
if let Some(api) = API.get() {
let handle = *self.handle.get_mut().unwrap_or_else(|e| e.into_inner());
let mut handle = handle as *mut c_void;
unsafe { (api.destroy)(&mut handle, null()) };
}
}
}
static CONTEXTS: Mutex<Option<HashMap<usize, Arc<Context>>>> = Mutex::new(None);
pub(super) fn init(dir: &Path) -> Result<(), String> {
use std::os::windows::ffi::OsStrExt;
let path = std::path::absolute(dir.join(UPSCALER_DLL)).map_err(|e| e.to_string())?;
streamline::verify_signature(&path)?;
let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
let module = unsafe {
LoadLibraryExW(
wide.as_ptr(),
null_mut(),
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
)
};
if module.is_null() {
return Err(std::io::Error::last_os_error().to_string());
}
let library = Module(module as usize);
let export = |name: &CStr| {
unsafe { GetProcAddress(module, name.as_ptr().cast()) }
.map(|f| f as *const ())
.ok_or_else(|| format!("missing {}", name.to_string_lossy()))
};
let device = streamline::host_upscale_device().ok_or("no host D3D12 device")?;
let device_ptr = windows::core::Interface::as_raw(&device);
let api = unsafe {
Api {
_library: library,
create: std::mem::transmute::<*const (), Create>(export(c"ffxCreateContext")?),
destroy: std::mem::transmute::<*const (), Destroy>(export(c"ffxDestroyContext")?),
configure: std::mem::transmute::<*const (), Call>(export(c"ffxConfigure")?),
query: std::mem::transmute::<*const (), Call>(export(c"ffxQuery")?),
dispatch: std::mem::transmute::<*const (), Call>(export(c"ffxDispatch")?),
device: device_ptr as usize,
}
};
let mut count = 0;
let mut versions = Versions {
header: Header {
kind: GET_VERSIONS,
next: null_mut(),
},
effect: CREATE_UPSCALE,
device: device_ptr,
count: &mut count,
ids: null_mut(),
names: null_mut(),
};
if unsafe { (api.query)(null_mut(), &mut versions.header) } != OK || count == 0 {
return Err("the selected device exposes no PC FidelityFX upscaler".to_owned());
}
let _ = API.set(api);
tracing::info!(count, dll = %path.display(), "PC FidelityFX upscaling available");
Ok(())
}
pub(super) fn active() -> bool {
API.get().is_some()
}
pub(super) fn create(
context: *mut *mut c_void,
mut asked: CreateUpscale,
memory: *const c_void,
) -> u32 {
let Some(api) = API.get() else {
return NO_PROVIDER;
};
if context.is_null() {
return PARAMETER;
}
let mut backend = Backend {
header: Header {
kind: 2,
next: asked.header.next,
},
device: api.device as *mut c_void,
};
if let Some(extension) = unsafe { asked.header.next.as_ref() }
&& extension.kind == 0x100_0002
{
backend.header.next = extension.next;
}
asked.header.next = &raw mut backend.header;
let code = unsafe { (api.create)(context, &mut asked.header, memory) };
if code != OK || context.is_null() {
tracing::warn!(code, render = ?asked.max_render, output = ?asked.max_output, "PC FidelityFX context creation failed");
return code;
}
let handle = unsafe { *context } as usize;
if handle == 0 {
return NO_PROVIDER;
}
let created = Created {
flags: asked.flags,
max_render: asked.max_render,
max_output: asked.max_output,
clamped: false,
};
CONTEXTS
.lock()
.unwrap_or_else(|e| e.into_inner())
.get_or_insert_with(HashMap::new)
.insert(
handle,
Arc::new(Context {
handle: Mutex::new(handle),
created,
}),
);
let provider = provider_version(api, context);
tracing::info!(
render = ?asked.max_render,
output = ?asked.max_output,
provider = provider.as_deref().unwrap_or("?"),
"PC FidelityFX upscaler created"
);
OK
}
fn provider_version(api: &Api, context: *mut *mut c_void) -> Option<String> {
#[repr(C)]
struct ProviderVersion {
header: Header,
id: u64,
name: *const std::ffi::c_char,
}
const _: () = assert!(size_of::<ProviderVersion>() == 32);
let mut asked = ProviderVersion { header: Header { kind: GET_PROVIDER_VERSION, next: null_mut() }, id: 0, name: null() };
if unsafe { (api.query)(context, &mut asked.header) } != OK || asked.name.is_null() {
return None;
}
Some(unsafe { CStr::from_ptr(asked.name) }.to_string_lossy().into_owned())
}
fn get(slot: *mut *mut c_void) -> Option<(usize, Arc<Context>)> {
let key = unsafe { *slot.as_ref()? } as usize;
let contexts = CONTEXTS.lock().unwrap_or_else(|e| e.into_inner());
Some((key, contexts.as_ref()?.get(&key)?.clone()))
}
pub(super) fn destroy(slot: *mut *mut c_void) -> Option<u32> {
let (key, context) = get(slot)?;
streamline::finish_host_upscale();
CONTEXTS
.lock()
.unwrap_or_else(|e| e.into_inner())
.as_mut()?
.remove(&key);
drop(context);
unsafe { *slot = null_mut() };
Some(OK)
}
pub(super) fn call(slot: *mut *mut c_void, desc: *mut Header, query: bool) -> Option<u32> {
let api = API.get()?;
if query
&& unsafe { desc.as_ref() }
.is_some_and(|header| matches!(header.kind, GET_VERSIONS | QUERY_MEMORY_USAGE))
{
return None;
}
let (_, context) = get(slot)?;
let handle = context.handle.lock().unwrap_or_else(|e| e.into_inner());
let mut handle = *handle as *mut c_void;
let call = if query { api.query } else { api.configure };
Some(unsafe { call(&mut handle, desc) })
}
struct Dispatch(DispatchUpscale);
unsafe impl Send for Dispatch {}
impl Dispatch {
fn record(
mut self,
api: &Api,
context: &Context,
list: &windows::Win32::Graphics::Direct3D12::ID3D12GraphicsCommandList,
textures: [Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource>; 7],
) -> bool {
use windows::core::Interface;
self.0.list = list.as_raw();
for (desc, texture) in self.0.resources.iter_mut().zip(&textures) {
desc.resource = texture.as_ref().map_or(null_mut(), Interface::as_raw);
}
let handle = context.handle.lock().unwrap_or_else(|e| e.into_inner());
let mut handle = *handle as *mut c_void;
let code = unsafe { (api.dispatch)(&mut handle, &mut self.0.header) };
if code == OK {
once!(info, render = ?self.0.render_size, output = ?self.0.upscale_size,
"PC FidelityFX recorded its first host upscale");
} else {
once!(warn, code, "PC FidelityFX refused a host upscale dispatch");
}
code == OK
}
}
pub(super) fn dispatch(slot: *mut *mut c_void, desc: *mut Header) -> Option<u32> {
let api = API.get()?;
let (key, context) = get(slot)?;
let Some(header) = (unsafe { desc.as_ref() }) else {
return Some(PARAMETER);
};
if header.kind != DISPATCH_UPSCALE || !header.next.is_null() {
return Some(PARAMETER);
}
let mut desc = unsafe { desc.cast::<DispatchUpscale>().read() };
let up = upscale(&desc, &context.created, key);
desc.list = null_mut();
for resource in &mut desc.resources {
resource.resource = null_mut();
}
let dispatch = Dispatch(desc);
let queued = streamline::record_host_upscale(up, move |list, textures| {
dispatch.record(api, &context, list, textures)
});
Some(if queued { OK } else { PARAMETER })
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,839 @@
use super::{
A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER,
RIGHT_STICK, UP, VIEW, X, Y,
};
const GENERIC_DESKTOP: u16 = 0x01;
const USAGE_X: u16 = 0x30;
const AXES: usize = 6;
const USAGE_HAT: u16 = 0x39;
const USAGE_START: u16 = 0x3D;
const USAGE_SELECT: u16 = 0x3E;
const DESKTOP_BUTTONS: [(u16, u32); 6] = [
(USAGE_START, MENU),
(USAGE_SELECT, VIEW),
(0x90, UP),
(0x91, DOWN),
(0x92, RIGHT),
(0x93, LEFT),
];
const BUTTON_PAGE: u16 = 0x09;
const PAD_USAGES: [u16; 2] = [0x04, 0x05];
pub(super) const ID: u64 = 1 << 63;
const AXIS_NAMES: [&str; AXES] = ["X", "Y", "Z", "Rx", "Ry", "Rz"];
const TARGETS: [u32; 16] = [
A,
B,
X,
Y,
LEFT_SHOULDER,
RIGHT_SHOULDER,
0,
0,
VIEW,
MENU,
LEFT_STICK,
RIGHT_STICK,
UP,
DOWN,
LEFT,
RIGHT,
];
const LEFT_TRIGGER: usize = 6;
const RIGHT_TRIGGER: usize = 7;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Layout([u16; 16]);
impl Layout {
const PLAYSTATION: Layout = Layout([3, 2, 4, 1, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0]);
const DIRECTINPUT: Layout = Layout([2, 3, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0]);
const NINTENDO: Layout = Layout([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0]);
fn for_pad(vendor: u16) -> Layout {
match vendor {
0x046D => Layout::DIRECTINPUT,
0x057E => Layout::NINTENDO,
_ => Layout::PLAYSTATION,
}
}
fn parse(text: &str) -> Option<Layout> {
let numbers = text
.split(',')
.map(|n| n.trim().parse::<u16>().ok())
.collect::<Option<Vec<u16>>>()?;
if numbers.len() != 12 && numbers.len() != 16 {
return None;
}
let mut layout = [0; 16];
layout[..numbers.len()].copy_from_slice(&numbers);
Some(Layout(layout))
}
fn text(&self) -> String {
let end = if self.0[12..].iter().all(|&n| n == 0) {
12
} else {
16
};
let numbers: Vec<String> = self.0[..end].iter().map(u16::to_string).collect();
numbers.join(",")
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Range {
min: i64,
max: i64,
signed: bool,
bits: u32,
}
impl Range {
fn new(min: i32, max: i32, bits: u16) -> Option<Range> {
let bits = u32::from(bits).clamp(1, 32);
let mask = (1i64 << bits) - 1;
let (mut min, mut max, mut signed) = (i64::from(min), i64::from(max), min < 0);
if max < min {
(min, max, signed) = (min & mask, max & mask, false);
}
(max > min).then_some(Range {
min,
max,
signed,
bits,
})
}
fn value(self, raw: u32) -> i64 {
let raw = i64::from(raw) & ((1i64 << self.bits) - 1);
if self.signed && raw >> (self.bits - 1) & 1 != 0 {
raw - (1i64 << self.bits)
} else {
raw
}
}
fn stick(self, value: i64) -> f32 {
let span = (self.max - self.min) as f64;
((2.0 * (value - self.min) as f64 / span - 1.0) as f32).clamp(-1.0, 1.0)
}
fn trigger(self, value: i64) -> f32 {
let span = (self.max - self.min) as f64;
(((value - self.min) as f64 / span) as f32).clamp(0.0, 1.0)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct Shape {
axes: [Option<Range>; AXES],
hat: Option<Range>,
}
impl Shape {
fn describe(&self) -> String {
let mut names: Vec<&str> = AXIS_NAMES
.iter()
.zip(self.axes)
.filter_map(|(name, range)| range.map(|_| *name))
.collect();
if self.hat.is_some() {
names.push("hat");
}
if names.is_empty() {
"no axes".to_owned()
} else {
names.join(" ")
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct Raw {
axes: [Option<i64>; AXES],
hat: Option<i64>,
buttons: Vec<u16>,
desktop: Vec<u16>,
}
fn hat(range: Range, value: i64) -> u32 {
if value < range.min || value > range.max {
return 0;
}
let step = value - range.min;
let eighths = if range.max - range.min + 1 == 4 {
step * 2
} else {
step
};
match eighths {
0 => UP,
1 => UP | RIGHT,
2 => RIGHT,
3 => RIGHT | DOWN,
4 => DOWN,
5 => DOWN | LEFT,
6 => LEFT,
7 => LEFT | UP,
_ => 0,
}
}
fn centred(shape: &Shape) -> [bool; AXES] {
let triggers = shape.axes[2].is_some() && shape.axes[5].is_some();
std::array::from_fn(|i| shape.axes[i].is_some() && !(triggers && (i == 3 || i == 4)))
}
pub(super) fn off_centre(shape: &Shape, axis: usize, value: i64) -> bool {
centred(shape)[axis] && shape.axes[axis].is_some_and(|r| r.stick(value).abs() > 0.5)
}
pub(super) fn state(shape: &Shape, raw: &Raw, layout: &Layout) -> PadState {
let has = |i: usize| shape.axes[i].is_some();
let stick = |i: usize| Some(shape.axes[i]?.stick(raw.axes[i]?));
let trigger = |i: usize| Some(shape.axes[i]?.trigger(raw.axes[i]?));
let (right, (left_trigger, right_trigger)) = if has(2) && has(5) {
let triggers = (trigger(3).unwrap_or(0.0), trigger(4).unwrap_or(0.0));
((stick(2), stick(5)), triggers)
} else {
let z = stick(2).unwrap_or(0.0);
((stick(3), stick(4)), (z.max(0.0), (-z).max(0.0)))
};
let held = |n: u16| n != 0 && raw.buttons.contains(&n);
let mut buttons = shape.hat.zip(raw.hat).map_or(0, |(range, v)| hat(range, v));
for (&n, bit) in layout.0.iter().zip(TARGETS) {
if held(n) {
buttons |= bit;
}
}
for (usage, bit) in DESKTOP_BUTTONS {
if raw.desktop.contains(&usage) {
buttons |= bit;
}
}
let pressed = |n: u16| if held(n) { 1.0 } else { 0.0 };
PadState {
buttons,
left_trigger: left_trigger.max(pressed(layout.0[LEFT_TRIGGER])),
right_trigger: right_trigger.max(pressed(layout.0[RIGHT_TRIGGER])),
left_x: stick(0).unwrap_or(0.0),
left_y: -stick(1).unwrap_or(0.0),
right_x: right.0.unwrap_or(0.0),
right_y: -right.1.unwrap_or(0.0),
}
}
pub(super) fn enabled() -> bool {
std::env::var_os("EONACAT_XS_GENERIC_PADS").is_none_or(|v| v != "0")
}
fn layout(vendor: u16) -> Layout {
let set = std::env::var("EONACAT_XS_PAD_BUTTONS")
.ok()
.filter(|t| !t.trim().is_empty());
match set.as_deref().map(|t| (t, Layout::parse(t))) {
Some((_, Some(layout))) => layout,
Some((text, None)) => {
tracing::warn!(
text,
"EONACAT_XS_PAD_BUTTONS: not 12 or 16 button numbers; the pad's own layout is used"
);
Layout::for_pad(vendor)
}
None => Layout::for_pad(vendor),
}
}
fn names(pad: &PadState) -> String {
const NAMES: [(u32, &str); 14] = [
(A, "A"),
(B, "B"),
(X, "X"),
(Y, "Y"),
(LEFT_SHOULDER, "LB"),
(RIGHT_SHOULDER, "RB"),
(VIEW, "View"),
(MENU, "Menu"),
(LEFT_STICK, "LS"),
(RIGHT_STICK, "RS"),
(UP, "Up"),
(DOWN, "Down"),
(LEFT, "Left"),
(RIGHT, "Right"),
];
let mut held: Vec<String> = NAMES
.iter()
.filter(|(bit, _)| pad.buttons & bit != 0)
.map(|(_, name)| (*name).to_owned())
.collect();
for (name, value) in [("LT", pad.left_trigger), ("RT", pad.right_trigger)] {
if value > 0.05 {
held.push(format!("{name} {value:.2}"));
}
}
if held.is_empty() {
"-".to_owned()
} else {
held.join(" ")
}
}
fn line(shape: &Shape, raw: &Raw, pad: &PadState) -> String {
let mut parts = vec![format!("buttons {:?}", raw.buttons)];
for ((name, range), value) in AXIS_NAMES.iter().zip(shape.axes).zip(raw.axes) {
if let (Some(range), Some(value)) = (range, value) {
parts.push(format!("{name} {:+.2}", range.stick(value)));
}
}
if let (Some(_), Some(value)) = (shape.hat, raw.hat) {
parts.push(format!("hat {value}"));
}
if !raw.desktop.is_empty() {
parts.push(format!("desktop {:02X?}", raw.desktop));
}
format!(
"{} -> {} (sticks L {:+.2} {:+.2} R {:+.2} {:+.2})",
parts.join(", "),
names(pad),
pad.left_x,
pad.left_y,
pad.right_x,
pad.right_y
)
}
#[cfg(windows)]
pub(super) use host::{monitor, pads};
#[cfg(windows)]
mod host {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{LazyLock, Mutex, PoisonError};
use std::time::{Duration, Instant};
use windows_sys::Win32::Devices::HumanInterfaceDevice::{
HIDD_ATTRIBUTES, HIDP_CAPS, HIDP_STATUS_SUCCESS, HIDP_VALUE_CAPS, HidD_FreePreparsedData,
HidD_GetAttributes, HidD_GetPreparsedData, HidD_GetProductString, HidP_GetCaps,
HidP_GetUsageValue, HidP_GetUsages, HidP_GetValueCaps, HidP_Input, HidP_MaxUsageListLength,
PHIDP_PREPARSED_DATA,
};
use windows_sys::Win32::Foundation::{CloseHandle, GENERIC_READ, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, ReadFile,
};
use super::super::playstation::{Sony, hid_paths};
use super::{
AXES, AXIS_NAMES, BUTTON_PAGE, GENERIC_DESKTOP, ID, Layout, PAD_USAGES, PadState, Range,
Raw, Shape, USAGE_HAT, USAGE_X, layout, line, off_centre, state,
};
const SCAN: Duration = Duration::from_secs(2);
struct Pad {
id: u64,
path: Vec<u16>,
name: String,
shape: Shape,
buttons: usize,
layout: Layout,
raw: Raw,
state: Option<PadState>,
}
static PADS: Mutex<Vec<Pad>> = Mutex::new(Vec::new());
fn lock() -> std::sync::MutexGuard<'static, Vec<Pad>> {
PADS.lock().unwrap_or_else(PoisonError::into_inner)
}
static OTHERS: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());
fn others() -> std::sync::MutexGuard<'static, Vec<Vec<u16>>> {
OTHERS.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(in super::super) fn pads() -> Vec<(u64, PadState)> {
static STARTED: LazyLock<()> = LazyLock::new(|| {
let started = std::thread::Builder::new()
.name("generic pad scan".into())
.spawn(|| {
loop {
scan();
std::thread::sleep(SCAN);
}
});
if let Err(error) = started {
tracing::warn!(%error, "no generic pads: the thread looking for them could not start");
}
});
LazyLock::force(&STARTED);
lock()
.iter()
.filter_map(|pad| Some((pad.id, pad.state?)))
.collect()
}
struct Handle(HANDLE);
unsafe impl Send for Handle {}
impl Drop for Handle {
fn drop(&mut self) {
unsafe { CloseHandle(self.0) };
}
}
impl Handle {
fn open(path: &[u16], access: u32) -> Option<Handle> {
let mut name = path.to_vec();
name.push(0);
let handle = unsafe {
CreateFileW(
name.as_ptr(),
access,
FILE_SHARE_READ | FILE_SHARE_WRITE,
std::ptr::null(),
OPEN_EXISTING,
0,
std::ptr::null_mut(),
)
};
(handle != INVALID_HANDLE_VALUE).then_some(Handle(handle))
}
}
struct Parser(PHIDP_PREPARSED_DATA);
unsafe impl Send for Parser {}
impl Drop for Parser {
fn drop(&mut self) {
unsafe { HidD_FreePreparsedData(self.0) };
}
}
impl Parser {
fn of(handle: &Handle) -> Option<Parser> {
let mut data = 0;
unsafe { HidD_GetPreparsedData(handle.0, &mut data) }.then_some(Parser(data))
}
fn value(&self, usage: u16, report: &[u8]) -> Option<u32> {
let mut value = 0;
let status = unsafe {
HidP_GetUsageValue(
HidP_Input,
GENERIC_DESKTOP,
0,
usage,
&mut value,
self.0,
report.as_ptr(),
report.len() as u32,
)
};
(status == HIDP_STATUS_SUCCESS).then_some(value)
}
fn usages(&self, page: u16, report: &mut [u8], list: &mut [u16]) -> Option<Vec<u16>> {
if list.is_empty() {
return None;
}
let mut count = list.len() as u32;
let status = unsafe {
HidP_GetUsages(
HidP_Input,
page,
0,
list.as_mut_ptr(),
&mut count,
self.0,
report.as_mut_ptr(),
report.len() as u32,
)
};
(status == HIDP_STATUS_SUCCESS).then(|| {
let mut held = list[..count as usize].to_vec();
held.sort_unstable();
held
})
}
fn buttons(&self, page: u16) -> usize {
unsafe { HidP_MaxUsageListLength(HidP_Input, page, self.0) as usize }
}
fn shape(&self, caps: &HIDP_CAPS) -> Shape {
let mut count = caps.NumberInputValueCaps;
let mut values = vec![HIDP_VALUE_CAPS::default(); usize::from(count)];
let status =
unsafe { HidP_GetValueCaps(HidP_Input, values.as_mut_ptr(), &mut count, self.0) };
let mut shape = Shape::default();
if status != HIDP_STATUS_SUCCESS {
return shape;
}
values.truncate(usize::from(count));
for cap in values.iter().filter(|cap| cap.UsagePage == GENERIC_DESKTOP) {
let (first, last) = unsafe {
if cap.IsRange {
(cap.Anonymous.Range.UsageMin, cap.Anonymous.Range.UsageMax)
} else {
(cap.Anonymous.NotRange.Usage, cap.Anonymous.NotRange.Usage)
}
};
let Some(range) = Range::new(cap.LogicalMin, cap.LogicalMax, cap.BitSize) else {
continue;
};
for usage in first..=last {
let slot = match usage {
USAGE_HAT => &mut shape.hat,
_ if (USAGE_X..USAGE_X + AXES as u16).contains(&usage) => {
&mut shape.axes[usize::from(usage - USAGE_X)]
}
_ => continue,
};
slot.get_or_insert(range);
}
}
shape
}
}
#[allow(clippy::large_enum_variant)]
enum Found {
Other,
Unknown,
Pad {
handle: Handle,
parser: Parser,
name: String,
vendor: u16,
product: u16,
input: usize,
shape: Shape,
},
}
fn look(path: &[u16]) -> Found {
let Some(query) = Handle::open(path, 0) else {
return Found::Unknown;
};
let mut attributes = HIDD_ATTRIBUTES {
Size: size_of::<HIDD_ATTRIBUTES>() as u32,
..Default::default()
};
if !unsafe { HidD_GetAttributes(query.0, &mut attributes) } {
return Found::Unknown;
}
let (vendor, product) = (attributes.VendorID, attributes.ProductID);
if Sony::of(vendor, product).is_some() {
return Found::Other;
}
let Some(parser) = Parser::of(&query) else {
return Found::Unknown;
};
let mut caps = HIDP_CAPS::default();
if unsafe { HidP_GetCaps(parser.0, &mut caps) } != HIDP_STATUS_SUCCESS {
return Found::Unknown;
}
if caps.UsagePage != GENERIC_DESKTOP
|| !PAD_USAGES.contains(&caps.Usage)
|| caps.InputReportByteLength == 0
{
return Found::Other;
}
let mut name = [0u16; 128];
let named = unsafe {
HidD_GetProductString(query.0, name.as_mut_ptr().cast(), size_of_val(&name) as u32)
};
let end = name.iter().position(|&c| c == 0).unwrap_or(name.len());
let name = if named {
String::from_utf16_lossy(&name[..end])
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
} else {
String::new()
};
let shape = parser.shape(&caps);
let Some(handle) = Handle::open(path, GENERIC_READ) else {
return Found::Unknown;
};
Found::Pad {
handle,
parser,
name,
vendor,
product,
input: usize::from(caps.InputReportByteLength),
shape,
}
}
fn scan() {
let paths = hid_paths();
others().retain(|path| paths.contains(path));
if paths.is_empty() {
return;
}
lock().retain(|pad| {
let present = paths.contains(&pad.path);
if !present {
tracing::info!(name = %pad.name, "generic pad gone");
}
present
});
for path in paths {
let lower = String::from_utf16_lossy(&path).to_ascii_lowercase();
if lower.contains("ig_")
|| lock().iter().any(|pad| pad.path == path)
|| others().contains(&path)
{
continue;
}
let (handle, parser, name, vendor, product, input, shape) = match look(&path) {
Found::Other => {
others().push(path);
continue;
}
Found::Unknown => continue,
Found::Pad {
handle,
parser,
name,
vendor,
product,
input,
shape,
} => (handle, parser, name, vendor, product, input, shape),
};
let layout = layout(vendor);
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let id = ID | NEXT_ID.fetch_add(1, Ordering::Relaxed);
let buttons = parser.buttons(BUTTON_PAGE);
tracing::info!(
path = %lower,
name = %name,
id = %format!("{vendor:04X}:{product:04X}"),
values = %shape.describe(),
buttons,
layout = %layout.text(),
"generic pad connected (EONACAT_XS_PAD_BUTTONS sets another layout; `eonacat-xsbox pads` shows its buttons)"
);
lock().push(Pad {
id,
path: path.clone(),
name: format!("{name} ({vendor:04X}:{product:04X})"),
shape,
buttons,
layout,
raw: Raw::default(),
state: None,
});
let reader = Reader {
id,
handle,
parser,
input,
shape,
layout,
};
if let Err(error) = std::thread::Builder::new()
.name("generic pad reader".into())
.spawn(move || reader.run())
{
lock().retain(|pad| pad.id != id);
tracing::warn!(%error, "could not start a generic pad reader");
}
}
}
struct Reader {
id: u64,
handle: Handle,
parser: Parser,
input: usize,
shape: Shape,
layout: Layout,
}
impl Reader {
fn run(self) {
let mut report = vec![0u8; self.input];
let mut buttons = vec![0u16; self.parser.buttons(BUTTON_PAGE)];
let mut desktop = vec![0u16; self.parser.buttons(GENERIC_DESKTOP)];
let mut raw = Raw::default();
let (mut seen, mut off) = ([false; AXES], [false; AXES]);
let why = loop {
let mut got = 0;
let read = unsafe {
ReadFile(
self.handle.0,
report.as_mut_ptr(),
report.len() as u32,
&mut got,
std::ptr::null_mut(),
)
};
if read == 0 {
break "read failed";
}
if got == 0 {
break "read nothing";
}
let got = (got as usize).min(report.len());
report[got..].fill(0);
let report = report.as_mut_slice();
for (i, range) in self.shape.axes.iter().enumerate() {
if let Some(range) = range
&& let Some(value) = self.parser.value(USAGE_X + i as u16, report)
{
let value = range.value(value);
raw.axes[i] = Some(value);
if !seen[i] {
seen[i] = true;
off[i] = off_centre(&self.shape, i, value);
if off[i] {
tracing::warn!(
axis = AXIS_NAMES[i],
"generic pad: an axis that should rest at its centre does not \
(a throttle or a pedal?); it is not read until the pad reconnects"
);
}
}
}
}
if let Some(range) = self.shape.hat
&& let Some(value) = self.parser.value(USAGE_HAT, report)
{
raw.hat = Some(range.value(value));
}
if let Some(held) = self.parser.usages(BUTTON_PAGE, report, &mut buttons) {
raw.buttons = held;
}
if let Some(held) = self.parser.usages(GENERIC_DESKTOP, report, &mut desktop) {
raw.desktop = held;
}
let mut read = raw.clone();
for (value, off) in read.axes.iter_mut().zip(off) {
if off {
*value = None;
}
}
let state = state(&self.shape, &read, &self.layout);
let mut pads = lock();
let Some(pad) = pads.iter_mut().find(|pad| pad.id == self.id) else {
break "forgotten";
};
pad.state = Some(state);
if pad.raw != raw {
pad.raw = raw.clone();
}
};
let name = lock()
.iter()
.find(|pad| pad.id == self.id)
.map(|pad| pad.name.clone())
.unwrap_or_default();
tracing::info!(why, name = %name, "generic pad disconnected");
lock().retain(|pad| pad.id != self.id);
}
}
pub(in super::super) fn monitor(seconds: u64) {
let found = Instant::now();
pads();
while lock().is_empty() && found.elapsed() < Duration::from_secs(3) {
std::thread::sleep(Duration::from_millis(100));
}
{
let pads = lock();
if pads.is_empty() {
println!("Generic HID pads: none found.");
return;
}
println!("Generic HID pads:");
for (n, pad) in pads.iter().enumerate() {
println!(
" pad {}: {}, {}, {} buttons, EONACAT_XS_PAD_BUTTONS={}",
n + 1,
pad.name,
pad.shape.describe(),
pad.buttons,
pad.layout.text()
);
}
}
println!(
"\nPress each button and move each stick ({seconds} s; Ctrl+C ends).\n\
EONACAT_XS_PAD_BUTTONS lists the button numbers for A,B,X,Y,LB,RB,LT,RT,View,Menu,LS,RS\n\
(Xbox names, by position: A south, B east, X west, Y north).\n"
);
let end = Instant::now() + Duration::from_secs(seconds);
let mut last: Vec<(u64, String)> = Vec::new();
while Instant::now() < end {
let now: Vec<(u64, String)> = lock()
.iter()
.enumerate()
.filter_map(|(n, pad)| {
let state = pad.state?;
Some((
pad.id,
format!("pad {}: {}", n + 1, line(&pad.shape, &pad.raw, &state)),
))
})
.collect();
for entry in &now {
if !last.contains(entry) {
println!("{}", entry.1);
}
}
last = now;
std::thread::sleep(Duration::from_millis(30));
}
}
}
@@ -0,0 +1,98 @@
use std::time::{Duration, Instant};
use eonacat_xsbox_gpu::SettingsPadMode;
use super::{A, B, DOWN, LEFT, LEFT_STICK, PadState, RIGHT, RIGHT_STICK, UP};
const STICKS: u32 = LEFT_STICK | RIGHT_STICK;
const NAVIGATION: u32 = UP | DOWN | LEFT | RIGHT | A | B;
const CHORD_WINDOW: Duration = Duration::from_millis(250);
const TOGGLE: u16 = 0x78;
#[derive(Default)]
pub(super) struct MenuPad {
previous: Option<u32>,
chord_armed: bool,
first_click: Option<Instant>,
captured: u32,
}
impl MenuPad {
pub(super) fn disconnected(&mut self, notify: impl FnOnce(Option<u16>)) {
if self.previous.take().is_some() {
notify(None);
}
self.captured = 0;
}
fn shortcut(&mut self, sticks: u32, previous: u32, clock: impl FnOnce() -> Instant) -> bool {
if sticks == 0 {
self.chord_armed = true;
self.first_click = None;
} else if self.chord_armed && sticks != previous {
if sticks != STICKS {
self.first_click = Some(clock());
} else {
self.chord_armed = false;
return self.first_click.is_none_or(|first| {
clock().saturating_duration_since(first) <= CHORD_WINDOW
});
}
}
false
}
pub(super) fn filter(
&mut self,
pad: &mut Option<PadState>,
mode: SettingsPadMode,
context: impl FnOnce() -> (bool, bool, bool),
clock: impl FnOnce() -> Instant,
notify: impl FnOnce(Option<u16>),
) {
if mode == SettingsPadMode::Off {
return;
}
let Some(pad) = pad else {
self.disconnected(notify);
return;
};
let (focused, open, pending) = context();
if !focused {
self.disconnected(notify);
return;
}
let buttons = pad.buttons;
let sticks = buttons & STICKS;
let Some(previous) = self.previous.replace(buttons) else {
self.first_click = None;
self.chord_armed = sticks == 0;
return;
};
let pressed = buttons & !previous & NAVIGATION;
self.captured &= buttons;
if mode == SettingsPadMode::StickShortcut && self.shortcut(sticks, previous & STICKS, clock) {
notify(Some(TOGGLE));
} else if open && !pending && pressed != 0 {
self.captured |= pressed;
let key = match buttons & NAVIGATION {
UP => Some(0x26),
DOWN => Some(0x28),
LEFT => Some(0x25),
RIGHT => Some(0x27),
A => Some(0x0d),
B => Some(0x1b),
_ => None,
};
if let Some(key) = key {
notify(Some(key));
}
}
pad.buttons &= !self.captured;
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,751 @@
use super::{
A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER,
RIGHT_STICK, UP, VIEW, X, Y,
};
const SONY: u16 = 0x054C;
const DONGLE: u16 = 0x0BA0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Sony {
DualShock4,
DualSense,
}
impl Sony {
pub(super) fn of(vendor: u16, product: u16) -> Option<Sony> {
match (vendor, product) {
(SONY, 0x05C4 | 0x09CC | DONGLE) => Some(Sony::DualShock4),
(SONY, 0x0CE6 | 0x0DF2) => Some(Sony::DualSense),
_ => None,
}
}
#[cfg(windows)]
fn full_reports_feature(self) -> u8 {
match self {
Sony::DualShock4 => 0x02,
Sony::DualSense => 0x05,
}
}
#[cfg(windows)]
fn pairing_feature(self) -> u8 {
match self {
Sony::DualShock4 => 0x12,
Sony::DualSense => 0x09,
}
}
#[cfg(windows)]
fn name(self) -> &'static str {
match self {
Sony::DualShock4 => "DualShock 4",
Sony::DualSense => "DualSense",
}
}
}
fn hat(value: u8) -> u32 {
match value & 0xF {
0 => UP,
1 => UP | RIGHT,
2 => RIGHT,
3 => RIGHT | DOWN,
4 => DOWN,
5 => DOWN | LEFT,
6 => LEFT,
7 => LEFT | UP,
_ => 0,
}
}
const BUTTONS: [(usize, u8, u32); 11] = [
(0, 0x10, X),
(0, 0x20, A),
(0, 0x40, B),
(0, 0x80, Y),
(1, 0x01, LEFT_SHOULDER),
(1, 0x02, RIGHT_SHOULDER),
(1, 0x10, VIEW),
(1, 0x20, MENU),
(1, 0x40, LEFT_STICK),
(1, 0x80, RIGHT_STICK),
(2, 0x02, VIEW),
];
pub(super) fn parse(pad: Sony, report: &[u8], bluetooth: bool) -> Option<PadState> {
let (sticks, triggers, buttons) = match (pad, report.first()?, bluetooth) {
(Sony::DualSense, 0x01, false) => (1, 5, 8),
(Sony::DualSense, 0x31, true) => (2, 6, 9),
(Sony::DualSense, 0x01, true) => (1, 8, 5),
(Sony::DualShock4, 0x01, _) => (1, 8, 5),
(Sony::DualShock4, 0x11, _) => (3, 10, 7),
_ => return None,
};
if report.len() < sticks + 4 || report.len() < triggers + 2 || report.len() < buttons + 3 {
return None;
}
let bytes = &report[buttons..buttons + 3];
let axis = |v: u8| ((f32::from(v) - 127.5) / 127.5).clamp(-1.0, 1.0);
Some(PadState {
buttons: BUTTONS
.iter()
.filter(|&&(byte, mask, _)| bytes[byte] & mask != 0)
.fold(hat(bytes[0]), |all, &(_, _, bit)| all | bit),
left_trigger: f32::from(report[triggers]) / 255.0,
right_trigger: f32::from(report[triggers + 1]) / 255.0,
left_x: axis(report[sticks]),
left_y: -axis(report[sticks + 1]),
right_x: axis(report[sticks + 2]),
right_y: -axis(report[sticks + 3]),
})
}
fn mac(pairing: &[u8]) -> Option<[u8; 6]> {
let mac: [u8; 6] = pairing.get(1..7)?.try_into().ok()?;
(mac != [0; 6]).then_some(mac)
}
fn serial_mac(serial: &str) -> Option<[u8; 6]> {
let digits: Vec<u8> = serial
.bytes()
.filter(|c| !matches!(c, b':' | b'-'))
.map(|c| char::from(c).to_digit(16).map(|d| d as u8))
.collect::<Option<_>>()?;
if digits.len() != 12 {
return None;
}
let mut mac = [0u8; 6];
for (byte, pair) in mac.iter_mut().rev().zip(digits.chunks(2)) {
*byte = pair[0] << 4 | pair[1];
}
(mac != [0; 6]).then_some(mac)
}
fn dongle_empty(report: &[u8]) -> bool {
report.len() >= 64 && report[0] == 0x01 && report[31] & 0x04 != 0
}
fn crc32(parts: &[&[u8]]) -> u32 {
let mut crc = !0u32;
for byte in parts.iter().flat_map(|p| p.iter()) {
crc ^= u32::from(*byte);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xEDB8_8320 & (crc & 1).wrapping_neg());
}
}
!crc
}
pub(super) fn rumble_report(
pad: Sony,
bluetooth: bool,
length: usize,
low: u16,
high: u16,
) -> Vec<u8> {
let (low, high) = ((low >> 8) as u8, (high >> 8) as u8);
let mut r = vec![0u8; if bluetooth { 78 } else { length.max(32) }];
let common = match (pad, bluetooth) {
(Sony::DualSense, false) => {
r[0] = 0x02;
1
}
(Sony::DualSense, true) => {
r[0] = 0x31;
r[1] = 0x00;
r[2] = 0x10;
3
}
(Sony::DualShock4, false) => {
r[0] = 0x05;
1
}
(Sony::DualShock4, true) => {
r[0] = 0x11;
r[1] = 0xC0;
3
}
};
r[common] = match pad {
Sony::DualSense => 0x03,
Sony::DualShock4 => 0x01,
};
let motors = match pad {
Sony::DualSense => common + 2,
Sony::DualShock4 => common + 3,
};
r[motors] = high;
r[motors + 1] = low;
if bluetooth {
let crc = crc32(&[&[0xA2], &r[..74]]);
r[74..].copy_from_slice(&crc.to_le_bytes());
r.resize(length.max(78), 0);
}
r
}
#[cfg(windows)]
pub(super) use host::{hid_paths, pads, rumble, stop_rumble};
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Mode {
Off,
Auto,
Both,
}
#[cfg(windows)]
pub(super) fn mode() -> Mode {
static MODE: std::sync::LazyLock<Mode> =
std::sync::LazyLock::new(|| match std::env::var("EONACAT_XS_DUALSENSE").as_deref() {
Ok("0") => Mode::Off,
Ok("1") => Mode::Both,
_ => Mode::Auto,
});
*MODE
}
pub(super) fn slots(
mode: Mode,
mut xinput: [Option<PadState>; super::PADS],
assigned: &mut [Option<u64>; super::PADS],
hid: impl FnOnce() -> Vec<(u64, PadState)>,
) -> [Option<PadState>; super::PADS] {
if mode == Mode::Off || mode == Mode::Auto && xinput.iter().any(Option::is_some) {
assigned.fill(None);
return xinput;
}
let pads = hid();
for (slot, owner) in xinput.iter_mut().zip(assigned.iter_mut()) {
if slot.is_none()
&& let Some((_, state)) = pads.iter().find(|(id, _)| Some(*id) == *owner)
{
*slot = Some(*state);
} else {
*owner = None;
}
}
for (id, state) in pads {
if assigned.contains(&Some(id)) {
continue;
}
let Some(slot) = xinput.iter().position(Option::is_none) else {
break;
};
xinput[slot] = Some(state);
assigned[slot] = Some(id);
}
xinput
}
#[cfg(windows)]
mod host {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{LazyLock, Mutex, PoisonError};
use std::time::Duration;
use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{
DIGCF_DEVICEINTERFACE, DIGCF_PRESENT, SP_DEVICE_INTERFACE_DATA,
SP_DEVICE_INTERFACE_DETAIL_DATA_W, SetupDiDestroyDeviceInfoList,
SetupDiEnumDeviceInterfaces, SetupDiGetClassDevsW, SetupDiGetDeviceInterfaceDetailW,
};
use windows_sys::Win32::Devices::HumanInterfaceDevice::{
HIDD_ATTRIBUTES, HIDP_CAPS, HIDP_STATUS_SUCCESS, HidD_FreePreparsedData,
HidD_GetAttributes, HidD_GetFeature, HidD_GetHidGuid, HidD_GetPreparsedData,
HidD_GetSerialNumberString, HidP_GetCaps,
};
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_IO_PENDING, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE,
INVALID_HANDLE_VALUE, WAIT_TIMEOUT,
};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, FILE_FLAG_OVERLAPPED, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
ReadFile, WriteFile,
};
use windows_sys::Win32::System::IO::{
CancelIoEx, GetOverlappedResult, GetOverlappedResultEx, OVERLAPPED,
};
use windows_sys::Win32::System::Threading::CreateEventW;
use super::{
DONGLE, PadState, SONY, Sony, dongle_empty, mac, parse, rumble_report, serial_mac,
};
const SCAN: Duration = Duration::from_secs(2);
const QUIET_MS: u32 = 500;
const WRITE_MS: u32 = 100;
struct Pad {
id: u64,
path: Vec<u16>,
mac: Option<[u8; 6]>,
state: Option<PadState>,
rumble: (u16, u16),
}
static PADS: Mutex<Vec<Pad>> = Mutex::new(Vec::new());
fn lock() -> std::sync::MutexGuard<'static, Vec<Pad>> {
PADS.lock().unwrap_or_else(PoisonError::into_inner)
}
static TWINS: Mutex<Vec<(Vec<u16>, [u8; 6])>> = Mutex::new(Vec::new());
pub(in super::super) fn pads() -> Vec<(u64, PadState)> {
static STARTED: LazyLock<()> = LazyLock::new(|| {
std::thread::spawn(|| {
loop {
scan();
std::thread::sleep(SCAN);
}
});
});
LazyLock::force(&STARTED);
lock()
.iter()
.filter_map(|pad| Some((pad.id, pad.state?)))
.collect()
}
pub(in super::super) fn rumble(id: u64, low: u16, high: u16) {
if let Some(pad) = lock().iter_mut().find(|pad| pad.id == id) {
pad.rumble = (low, high);
}
}
pub(in super::super) fn stop_rumble() -> bool {
let mut pads = lock();
let any = pads.iter().any(|pad| pad.rumble != (0, 0));
for pad in pads.iter_mut() {
pad.rumble = (0, 0);
}
any
}
struct Reports {
input: Vec<u8>,
feature: Vec<u8>,
output: usize,
}
impl Reports {
fn for_device(handle: HANDLE) -> Option<Self> {
let mut data = 0;
if !unsafe { HidD_GetPreparsedData(handle, &mut data) } {
return None;
}
let mut caps = HIDP_CAPS::default();
let status = unsafe { HidP_GetCaps(data, &mut caps) };
unsafe { HidD_FreePreparsedData(data) };
if status != HIDP_STATUS_SUCCESS
|| caps.InputReportByteLength == 0
|| caps.FeatureReportByteLength == 0
{
return None;
}
Some(Self {
input: vec![0; usize::from(caps.InputReportByteLength)],
feature: vec![0; usize::from(caps.FeatureReportByteLength)],
output: usize::from(caps.OutputReportByteLength),
})
}
}
fn feature(handle: HANDLE, id: u8, buffer: &mut [u8]) -> bool {
buffer.fill(0);
buffer[0] = id;
unsafe { HidD_GetFeature(handle, buffer.as_mut_ptr().cast(), buffer.len() as u32) }
}
fn full_reports(handle: HANDLE, pad: Sony, buffer: &mut [u8]) -> bool {
feature(handle, pad.full_reports_feature(), buffer)
}
fn address(handle: HANDLE, pad: Sony, bluetooth: bool, buffer: &mut [u8]) -> Option<[u8; 6]> {
if pad == Sony::DualShock4 && bluetooth {
let mut serial = [0u16; 128];
let ok = unsafe {
HidD_GetSerialNumberString(
handle,
serial.as_mut_ptr().cast(),
size_of_val(&serial) as u32,
)
};
let end = serial.iter().position(|&c| c == 0).unwrap_or(serial.len());
return ok
.then(|| serial_mac(&String::from_utf16_lossy(&serial[..end])))
.flatten();
}
feature(handle, pad.pairing_feature(), buffer)
.then(|| mac(buffer))
.flatten()
}
fn write(handle: HANDLE, event: HANDLE, report: &[u8]) -> bool {
let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
overlapped.hEvent = event;
let mut put = 0;
let started = unsafe {
WriteFile(
handle,
report.as_ptr(),
report.len() as u32,
std::ptr::null_mut(),
&mut overlapped,
)
};
if started == 0 && unsafe { GetLastError() } != ERROR_IO_PENDING {
return false;
}
if unsafe { GetOverlappedResultEx(handle, &overlapped, &mut put, WRITE_MS, 0) } != 0 {
return true;
}
unsafe {
CancelIoEx(handle, &overlapped);
GetOverlappedResult(handle, &overlapped, &mut put, 1);
}
false
}
fn scan() {
let paths = hid_paths();
{
let pads = lock();
TWINS
.lock()
.unwrap_or_else(PoisonError::into_inner)
.retain(|(path, mac)| {
paths.contains(path) && pads.iter().any(|pad| pad.mac == Some(*mac))
});
}
for path in paths {
let lower = String::from_utf16_lossy(&path).to_ascii_lowercase();
if !lower.contains("054c") {
continue;
}
if lock().iter().any(|pad| pad.path == path)
|| TWINS
.lock()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.any(|(twin, _)| *twin == path)
{
continue;
}
let Some((handle, mut reports, pad, dongle)) = open(&path) else {
continue;
};
let bluetooth = lower.contains("{00001124-") || reports.input.len() > 64;
let link = Link {
pad,
dongle,
bluetooth,
};
let name = pad.name();
if !full_reports(handle, pad, &mut reports.feature) {
tracing::debug!(path = %lower, pad = name, "PlayStation pad listed but not answering");
unsafe { CloseHandle(handle) };
continue;
}
let mac = address(handle, pad, bluetooth, &mut reports.feature);
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
let id = {
let mut pads = lock();
let twin = mac.is_some() && pads.iter().any(|pad| pad.mac == mac);
(!twin).then(|| {
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
pads.push(Pad {
id,
path: path.clone(),
mac,
state: None,
rumble: (0, 0),
});
id
})
};
let Some(id) = id else {
tracing::info!(path = %lower, pad = name, bluetooth, "PlayStation pad already open over the other transport");
if let Some(mac) = mac {
TWINS
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push((path, mac));
}
unsafe { CloseHandle(handle) };
continue;
};
tracing::info!(path = %lower, pad = name, bluetooth, "PlayStation pad connected");
let raw = handle as usize;
if let Err(error) = std::thread::Builder::new()
.name("PlayStation pad reader".into())
.spawn(move || read(raw as HANDLE, id, link, reports))
{
lock().retain(|pad| pad.id != id);
unsafe { CloseHandle(handle) };
tracing::warn!(%error, "could not start a PlayStation pad reader");
}
}
}
#[derive(Clone, Copy)]
struct Link {
pad: Sony,
dongle: bool,
bluetooth: bool,
}
fn read(handle: HANDLE, id: u64, link: Link, mut reports: Reports) {
let Link {
pad: kind,
dongle,
bluetooth,
} = link;
let set = |state: Option<PadState>| {
lock().iter_mut().find(|pad| pad.id == id).map(|pad| {
pad.state = state;
pad.rumble
})
};
let (event, wrote) = unsafe {
(
CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()),
CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()),
)
};
let (mut sent, mut wanted) = ((0, 0), (0, 0));
let mut write_failed = false;
let why = 'pad: loop {
if event.is_null() {
break 'pad "no event";
}
if wanted != sent && reports.output > 0 && !wrote.is_null() {
sent = wanted;
let report = rumble_report(kind, bluetooth, reports.output, wanted.0, wanted.1);
if !write(handle, wrote, &report) && !write_failed {
write_failed = true;
tracing::info!(
pad = kind.name(),
bluetooth,
"a PlayStation pad rumble report did not go out"
);
}
}
let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
overlapped.hEvent = event;
let mut got = 0;
let started = unsafe {
ReadFile(
handle,
reports.input.as_mut_ptr(),
reports.input.len() as u32,
std::ptr::null_mut(),
&mut overlapped,
)
};
if started == 0 && unsafe { GetLastError() } != ERROR_IO_PENDING {
break 'pad "read failed";
}
loop {
let done =
unsafe { GetOverlappedResultEx(handle, &overlapped, &mut got, QUIET_MS, 0) };
if done != 0 {
if got == 0 {
break 'pad "read nothing";
}
break;
}
if unsafe { GetLastError() } != WAIT_TIMEOUT {
break 'pad "read failed";
}
set(None);
if !full_reports(handle, kind, &mut reports.feature) {
unsafe {
CancelIoEx(handle, &overlapped);
GetOverlappedResult(handle, &overlapped, &mut got, 1);
}
break 'pad "not answering";
}
}
let report = &reports.input[..got as usize];
let state = if dongle && dongle_empty(report) {
Some(None)
} else {
parse(kind, report, bluetooth).map(Some)
};
if let Some(state) = state
&& let Some(asked) = set(state)
{
wanted = asked;
}
};
tracing::info!(
why,
pad = kind.name(),
bluetooth,
"PlayStation pad disconnected"
);
lock().retain(|pad| pad.id != id);
unsafe {
for event in [event, wrote] {
if !event.is_null() {
CloseHandle(event);
}
}
CloseHandle(handle);
}
}
fn open(path: &[u16]) -> Option<(HANDLE, Reports, Sony, bool)> {
let mut name = path.to_vec();
name.push(0);
let handle = unsafe {
CreateFileW(
name.as_ptr(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
std::ptr::null(),
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
std::ptr::null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
return None;
}
let mut attributes = HIDD_ATTRIBUTES {
Size: size_of::<HIDD_ATTRIBUTES>() as u32,
..Default::default()
};
let ours = unsafe { HidD_GetAttributes(handle, &mut attributes) }
.then(|| Sony::of(attributes.VendorID, attributes.ProductID))
.flatten();
if let Some(pad) = ours
&& let Some(reports) = Reports::for_device(handle)
{
let dongle = attributes.VendorID == SONY && attributes.ProductID == DONGLE;
return Some((handle, reports, pad, dongle));
}
unsafe { CloseHandle(handle) };
None
}
pub(in super::super) fn hid_paths() -> Vec<Vec<u16>> {
let mut paths = Vec::new();
unsafe {
let mut guid = std::mem::zeroed();
HidD_GetHidGuid(&mut guid);
let set = SetupDiGetClassDevsW(
&guid,
std::ptr::null(),
std::ptr::null_mut(),
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE,
);
if set == INVALID_HANDLE_VALUE as isize {
return paths;
}
for index in 0.. {
let mut interface = SP_DEVICE_INTERFACE_DATA {
cbSize: size_of::<SP_DEVICE_INTERFACE_DATA>() as u32,
..std::mem::zeroed()
};
if SetupDiEnumDeviceInterfaces(set, std::ptr::null(), &guid, index, &mut interface)
== 0
{
break;
}
let mut size = 0;
SetupDiGetDeviceInterfaceDetailW(
set,
&interface,
std::ptr::null_mut(),
0,
&mut size,
std::ptr::null_mut(),
);
if size == 0 {
continue;
}
let mut buffer = vec![0u64; (size as usize).div_ceil(8)];
let detail = buffer
.as_mut_ptr()
.cast::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>();
(*detail).cbSize = size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>() as u32;
if SetupDiGetDeviceInterfaceDetailW(
set,
&interface,
detail,
size,
std::ptr::null_mut(),
std::ptr::null_mut(),
) == 0
{
continue;
}
let start = std::ptr::addr_of!((*detail).DevicePath).cast::<u16>();
let room = (size as usize
- std::mem::offset_of!(SP_DEVICE_INTERFACE_DETAIL_DATA_W, DevicePath))
/ 2;
let wide = std::slice::from_raw_parts(start, room);
let end = wide.iter().position(|&c| c == 0).unwrap_or(room);
paths.push(wide[..end].to_vec());
}
SetupDiDestroyDeviceInfoList(set);
}
paths
}
}
@@ -0,0 +1,434 @@
#![allow(non_snake_case)]
use std::sync::{Mutex, Once};
use std::time::Duration;
use windows_sys::Win32::Devices::DeviceAndDriverInstallation::{
DIGCF_DEVICEINTERFACE, DIGCF_PRESENT, HDEVINFO, SP_DEVICE_INTERFACE_DATA,
SP_DEVICE_INTERFACE_DETAIL_DATA_W, SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInterfaces,
SetupDiGetClassDevsW, SetupDiGetDeviceInterfaceDetailW,
};
use windows_sys::Win32::Devices::HumanInterfaceDevice::{
GUID_DEVINTERFACE_HID, HID_USAGE_GENERIC_HATSWITCH, HID_USAGE_GENERIC_RX, HID_USAGE_GENERIC_RY,
HID_USAGE_GENERIC_RZ, HID_USAGE_GENERIC_X, HID_USAGE_GENERIC_Y, HID_USAGE_GENERIC_Z,
HID_USAGE_PAGE_BUTTON, HID_USAGE_PAGE_GENERIC, HIDD_ATTRIBUTES, HIDP_CAPS, HIDP_STATUS_SUCCESS,
HidD_FreePreparsedData, HidD_GetAttributes, HidD_GetPreparsedData, HidD_GetProductString,
HidP_GetCaps, HidP_GetUsageValue, HidP_GetUsages, HidP_Input,
};
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, ReadFile,
};
use super::{
A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER,
RIGHT_STICK, UP, VIEW, X, Y,
};
const GOOGLE: u16 = 0x18d1;
const STADIA: u16 = 0x9400;
const PAGE_SIMULATION: u16 = 0x02;
const USAGE_ACCELERATOR: u16 = 0xc4;
const USAGE_BRAKE: u16 = 0xc5;
const GENERIC_READ: u32 = 0x8000_0000;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Reading {
buttons: u32,
left_trigger: f32,
right_trigger: f32,
left_x: f32,
left_y: f32,
right_x: f32,
right_y: f32,
}
static READING: Mutex<Option<Reading>> = Mutex::new(None);
static START: Once = Once::new();
fn wanted() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("EONACAT_XS_HID_PADS").is_none_or(|v| v != "0"))
}
pub(super) fn latest() -> Option<PadState> {
if !wanted() {
return None;
}
START.call_once(|| {
let _ = std::thread::Builder::new()
.name("stadia".into())
.spawn(reader);
});
let r = (*READING.lock().unwrap_or_else(|e| e.into_inner()))?;
Some(PadState {
buttons: r.buttons,
left_trigger: r.left_trigger,
right_trigger: r.right_trigger,
left_x: r.left_x,
left_y: r.left_y,
right_x: r.right_x,
right_y: r.right_y,
})
}
struct Pad {
handle: HANDLE,
preparsed: isize,
input_len: usize,
}
impl Drop for Pad {
fn drop(&mut self) {
unsafe {
HidD_FreePreparsedData(self.preparsed);
CloseHandle(self.handle);
}
}
}
fn reader() {
loop {
if let Some(pad) = open_pad() {
read_reports(&pad, None);
}
*READING.lock().unwrap_or_else(|e| e.into_inner()) = None;
std::thread::sleep(Duration::from_secs(2));
}
}
fn read_reports(pad: &Pad, until: Option<std::time::Instant>) {
let mut buf = vec![0u8; pad.input_len.max(64)];
let log = std::env::var_os("EONACAT_XS_PAD_LOG").is_some_and(|v| v != "0");
let mut last: Option<Reading> = None;
let mut last_usages: Vec<u16> = Vec::new();
loop {
if until.is_some_and(|t| std::time::Instant::now() > t) {
return;
}
let mut read = 0u32;
let ok = unsafe {
ReadFile(
pad.handle,
buf.as_mut_ptr().cast(),
buf.len() as u32,
&mut read,
std::ptr::null_mut(),
)
};
if ok == 0 || read == 0 {
return;
}
let report = &buf[..read as usize];
let usages = usage_buttons(pad.preparsed, report);
let reading = parse(pad.preparsed, report, &usages);
if (log || until.is_some()) && usages != last_usages {
let raw: Vec<String> = report.iter().map(|b| format!("{b:02x}")).collect();
let text = format!(
"Stadia report: usages {usages:?} -> buttons {:#x}; left {:.2},{:.2} right {:.2},{:.2} triggers {:.2},{:.2}; raw {}",
reading.buttons,
reading.left_x,
reading.left_y,
reading.right_x,
reading.right_y,
reading.left_trigger,
reading.right_trigger,
raw.join(" ")
);
if until.is_some() {
println!("{text}");
} else {
tracing::info!("{text}");
}
}
last_usages = usages;
if last == Some(reading) {
continue;
}
last = Some(reading);
*READING.lock().unwrap_or_else(|e| e.into_inner()) = Some(reading);
}
}
fn is_stadia(handle: HANDLE, attributes: &HIDD_ATTRIBUTES) -> bool {
if attributes.VendorID == GOOGLE && attributes.ProductID == STADIA {
return true;
}
let mut name = [0u16; 128];
let ok =
unsafe { HidD_GetProductString(handle, name.as_mut_ptr().cast(), (name.len() * 2) as u32) };
if !ok {
return false;
}
let len = name.iter().position(|&c| c == 0).unwrap_or(name.len());
String::from_utf16_lossy(&name[..len])
.to_ascii_lowercase()
.contains("stadia")
}
fn open_pad() -> Option<Pad> {
for path in device_paths() {
let mut wide = path.clone();
wide.push(0);
let handle = unsafe {
CreateFileW(
wide.as_ptr(),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
std::ptr::null(),
OPEN_EXISTING,
0,
std::ptr::null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
continue;
}
let mut attributes: HIDD_ATTRIBUTES = unsafe { std::mem::zeroed() };
attributes.Size = std::mem::size_of::<HIDD_ATTRIBUTES>() as u32;
let known = unsafe { HidD_GetAttributes(handle, &mut attributes) };
if known && is_stadia(handle, &attributes) {
let mut preparsed: isize = 0;
if !unsafe { HidD_GetPreparsedData(handle, &mut preparsed) } {
unsafe { CloseHandle(handle) };
continue;
}
let mut caps: HIDP_CAPS = unsafe { std::mem::zeroed() };
let status = unsafe { HidP_GetCaps(preparsed, &mut caps) };
const GAMEPAD: u16 = 0x05;
const JOYSTICK: u16 = 0x04;
if status != HIDP_STATUS_SUCCESS
|| caps.UsagePage != HID_USAGE_PAGE_GENERIC
|| !matches!(caps.Usage, GAMEPAD | JOYSTICK)
{
unsafe {
HidD_FreePreparsedData(preparsed);
CloseHandle(handle);
}
continue;
}
let input_len = usize::from(caps.InputReportByteLength).max(1);
tracing::info!(
vendor = format_args!("{:#06x}", attributes.VendorID),
product = format_args!("{:#06x}", attributes.ProductID),
report = input_len,
"Stadia controller connected over HID"
);
return Some(Pad {
handle,
preparsed,
input_len,
});
}
unsafe { CloseHandle(handle) };
}
None
}
fn device_paths() -> Vec<Vec<u16>> {
let mut paths = Vec::new();
let set: HDEVINFO = unsafe {
SetupDiGetClassDevsW(
&GUID_DEVINTERFACE_HID,
std::ptr::null(),
std::ptr::null_mut(),
DIGCF_PRESENT | DIGCF_DEVICEINTERFACE,
)
};
if set == -1 {
return paths;
}
let mut index = 0u32;
loop {
let mut interface: SP_DEVICE_INTERFACE_DATA = unsafe { std::mem::zeroed() };
interface.cbSize = std::mem::size_of::<SP_DEVICE_INTERFACE_DATA>() as u32;
if unsafe {
SetupDiEnumDeviceInterfaces(
set,
std::ptr::null(),
&GUID_DEVINTERFACE_HID,
index,
&mut interface,
)
} == 0
{
break;
}
index += 1;
let mut required = 0u32;
unsafe {
SetupDiGetDeviceInterfaceDetailW(
set,
&interface,
std::ptr::null_mut(),
0,
&mut required,
std::ptr::null_mut(),
)
};
if required == 0 {
continue;
}
let mut buffer = vec![0u8; required as usize];
let detail = buffer
.as_mut_ptr()
.cast::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>();
unsafe {
(*detail).cbSize = std::mem::size_of::<SP_DEVICE_INTERFACE_DETAIL_DATA_W>() as u32;
if SetupDiGetDeviceInterfaceDetailW(
set,
&interface,
detail,
required,
std::ptr::null_mut(),
std::ptr::null_mut(),
) == 0
{
continue;
}
}
let words = (buffer.len() - 4) / 2;
let path =
unsafe { std::slice::from_raw_parts(buffer.as_ptr().add(4).cast::<u16>(), words) };
let len = path.iter().position(|&c| c == 0).unwrap_or(words);
paths.push(path[..len].to_vec());
}
unsafe { SetupDiDestroyDeviceInfoList(set) };
paths
}
fn usage_value(preparsed: isize, report: &[u8], page: u16, usage: u16) -> Option<u32> {
let mut value = 0u32;
let status = unsafe {
HidP_GetUsageValue(
HidP_Input,
page,
0,
usage,
&mut value,
preparsed,
report.as_ptr(),
report.len() as u32,
)
};
(status == HIDP_STATUS_SUCCESS).then_some(value)
}
fn usage_buttons(preparsed: isize, report: &[u8]) -> Vec<u16> {
let mut usages = [0u16; 32];
let mut len = usages.len() as u32;
let status = unsafe {
HidP_GetUsages(
HidP_Input,
HID_USAGE_PAGE_BUTTON,
0,
usages.as_mut_ptr(),
&mut len,
preparsed,
report.as_ptr() as *mut u8,
report.len() as u32,
)
};
if status == HIDP_STATUS_SUCCESS {
usages[..len as usize].to_vec()
} else {
Vec::new()
}
}
fn parse(preparsed: isize, report: &[u8], usages: &[u16]) -> Reading {
let generic = |usage| usage_value(preparsed, report, HID_USAGE_PAGE_GENERIC, usage);
let axis = |usage| generic(usage).unwrap_or(128);
let trigger = |simulation: u16, generic_usage: u16| {
usage_value(preparsed, report, PAGE_SIMULATION, simulation)
.or_else(|| generic(generic_usage))
.unwrap_or(0)
};
state(
[
axis(HID_USAGE_GENERIC_X),
axis(HID_USAGE_GENERIC_Y),
axis(HID_USAGE_GENERIC_Z),
axis(HID_USAGE_GENERIC_RZ),
],
[
trigger(USAGE_BRAKE, HID_USAGE_GENERIC_RX),
trigger(USAGE_ACCELERATOR, HID_USAGE_GENERIC_RY),
],
generic(HID_USAGE_GENERIC_HATSWITCH).unwrap_or(15),
usages,
)
}
fn state(sticks: [u32; 4], triggers: [u32; 2], hat: u32, usages: &[u16]) -> Reading {
let centered = |v: u32| ((f32::from(v.min(255) as u8) - 127.5) / 127.5).clamp(-1.0, 1.0);
let mut buttons = 0u32;
for usage in usages {
buttons |= match usage {
1 => A,
2 => B,
4 => X,
5 => Y,
7 => LEFT_SHOULDER,
8 => RIGHT_SHOULDER,
11 => VIEW,
12 => MENU,
13 => MENU,
14 => LEFT_STICK,
15 => RIGHT_STICK,
_ => 0,
};
}
buttons |= match hat {
0 => UP,
1 => UP | RIGHT,
2 => RIGHT,
3 => DOWN | RIGHT,
4 => DOWN,
5 => DOWN | LEFT,
6 => LEFT,
7 => UP | LEFT,
_ => 0,
};
Reading {
buttons,
left_trigger: f32::from(triggers[0].min(255) as u8) / 255.0,
right_trigger: f32::from(triggers[1].min(255) as u8) / 255.0,
left_x: centered(sticks[0]),
left_y: -centered(sticks[1]),
right_x: centered(sticks[2]),
right_y: -centered(sticks[3]),
}
}
@@ -0,0 +1,21 @@
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum XInputRoute {
Gameplay,
MenuOnly,
Off,
}
impl XInputRoute {
pub(super) fn for_poll(dualsense_only: bool, native_mouse: bool, mnk_bindings: bool) -> Self {
if dualsense_only {
Self::Off
} else if !native_mouse && mnk_bindings {
Self::MenuOnly
} else {
Self::Gameplay
}
}
}
+311
View File
@@ -0,0 +1,311 @@
use std::path::{Component, Path, PathBuf};
const LOGOS: [(&str, u32); 3] = [
("Square44x44Logo", 44),
("Square150x150Logo", 150),
("Square480x480Logo", 480),
];
const LAST_RESORT: (&str, u32) = ("StoreLogo", 50);
fn element_attributes(xml: &str, element: &str) -> Vec<(String, String)> {
let open = format!("<{element}");
let mut from = 0;
let start = loop {
let Some(at) = xml[from..].find(&open) else {
return Vec::new();
};
let after = from + at + open.len();
match xml[after..].chars().next() {
Some(c) if c.is_whitespace() || c == '/' || c == '>' => break after,
_ => from = after,
}
};
let mut quote = None;
let mut end = xml.len();
for (i, c) in xml[start..].char_indices() {
match (quote, c) {
(None, '"' | '\'') => quote = Some(c),
(Some(q), _) if c == q => quote = None,
(None, '>') => {
end = start + i;
break;
}
_ => {}
}
}
let mut rest = &xml[start..end];
let mut out = Vec::new();
while let Some(eq) = rest.find('=') {
let name = rest[..eq].trim().to_owned();
let value = rest[eq + 1..].trim_start();
let Some(q) = value.chars().next().filter(|c| *c == '"' || *c == '\'') else {
break;
};
let Some(close) = value[1..].find(q) else { break };
out.push((name, value[1..1 + close].replace("&amp;", "&")));
rest = &value[close + 2..];
}
out
}
fn logos_from_manifest(xml: &str) -> Vec<(u32, String)> {
let attrs = element_attributes(xml, "ShellVisuals");
let get = |key: &str| {
attrs
.iter()
.find(|(k, v)| k == key && !v.trim().is_empty())
.map(|(_, v)| v.trim().to_owned())
};
let mut found: Vec<(u32, String)> = LOGOS
.iter()
.filter_map(|(key, size)| get(key).map(|v| (*size, v)))
.collect();
if found.is_empty()
&& let Some(v) = get(LAST_RESORT.0)
{
found.push((LAST_RESORT.1, v));
}
found
}
fn safe_relative(relative: &str) -> Option<PathBuf> {
let text = relative.trim().replace('/', "\\");
if text.is_empty() || text.starts_with('\\') || text.contains(':') {
return None;
}
let path = PathBuf::from(&text);
path.components()
.all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
.then_some(path)
}
fn pick_source(sizes: &[u32], want: u32) -> Option<usize> {
sizes
.iter()
.enumerate()
.filter(|(_, s)| **s >= want)
.min_by_key(|(_, s)| **s)
.or_else(|| sizes.iter().enumerate().max_by_key(|(_, s)| **s))
.map(|(i, _)| i)
}
fn find_manifest(dir: &Path) -> Option<PathBuf> {
std::fs::read_dir(dir).ok()?.flatten().find_map(|e| {
e.file_name()
.to_str()
.is_some_and(|n| n.eq_ignore_ascii_case("MicrosoftGame.config"))
.then(|| e.path())
})
}
fn game_logos(dir: &Path) -> Vec<(u32, PathBuf)> {
let Some(text) = find_manifest(dir).and_then(|p| std::fs::read(p).ok()) else {
return Vec::new();
};
let text = String::from_utf8_lossy(&text);
let text = text.trim_start_matches('\u{feff}');
let root = dir.canonicalize().ok();
logos_from_manifest(text)
.into_iter()
.filter_map(|(size, rel)| {
let Some(rel) = safe_relative(&rel) else {
tracing::warn!("icon: the manifest names a path outside the game folder; skipped");
return None;
};
let full = dir.join(rel).canonicalize().ok()?;
root.as_ref().is_some_and(|r| full.starts_with(r)).then_some((size, full))
})
.collect()
}
#[cfg(windows)]
pub use imp::{is_ours, start};
#[cfg(windows)]
mod imp {
use super::*;
use std::sync::atomic::{AtomicIsize, Ordering};
use windows::Win32::Foundation::GENERIC_READ;
use windows::Win32::Graphics::Imaging::{
CLSID_WICImagingFactory, GUID_WICPixelFormat32bppBGRA, GUID_WICPixelFormat32bppPBGRA,
IWICBitmapSource, IWICImagingFactory, IWICPalette, WICBitmapDitherTypeNone,
WICBitmapInterpolationModeFant, WICBitmapPaletteTypeCustom, WICDecodeMetadataCacheOnDemand,
};
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx};
use windows::core::{Interface, PCWSTR};
use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM};
use windows_sys::Win32::Graphics::Gdi::{
BI_RGB, BITMAPINFO, CreateBitmap, CreateDIBSection, DIB_RGB_COLORS, DeleteObject, GetDC, ReleaseDC,
};
use windows_sys::Win32::UI::HiDpi::{GetDpiForWindow, GetSystemMetricsForDpi};
use windows_sys::Win32::UI::WindowsAndMessaging as wm;
static BIG: AtomicIsize = AtomicIsize::new(0);
static SMALL: AtomicIsize = AtomicIsize::new(0);
pub fn is_ours(icon: LPARAM) -> bool {
icon != 0 && (icon == BIG.load(Ordering::Relaxed) || icon == SMALL.load(Ordering::Relaxed))
}
fn game_dir() -> Option<PathBuf> {
let base = crate::hle::runtime::main_image()?;
crate::hle::runtime::image_path(base)?.parent().map(Path::to_path_buf)
}
pub fn start(hwnd: HWND) {
let setting = std::env::var_os("EONACAT_XS_ICON");
let setting = setting.as_deref().and_then(|s| s.to_str()).map(str::trim);
let source = match setting {
Some("0") => return,
None | Some("") | Some("game") => None,
Some(path) => Some(PathBuf::from(path)),
};
let hwnd = hwnd as usize;
let spawned = std::thread::Builder::new().name("eonacat-xs-icon".into()).spawn(move || {
if let Err(why) = run(hwnd as HWND, source) {
tracing::warn!("icon: not set ({why})");
}
});
if let Err(e) = spawned {
tracing::warn!("icon: no thread ({e})");
}
}
fn run(hwnd: HWND, file: Option<PathBuf>) -> Result<(), String> {
let dpi = unsafe { GetDpiForWindow(hwnd) }.max(96);
let (big, small) = unsafe {
(
GetSystemMetricsForDpi(wm::SM_CXICON, dpi).max(16) as u32,
GetSystemMetricsForDpi(wm::SM_CXSMICON, dpi).max(16) as u32,
)
};
let (big_icon, small_icon) = match file {
Some(path) if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("ico")) => {
(load_ico(&path, big)?, load_ico(&path, small)?)
}
Some(path) => {
let sources = vec![(0, path)];
(png_icon(&sources, big)?, png_icon(&sources, small)?)
}
None => {
let dir = game_dir().ok_or("no game folder")?;
let sources = game_logos(&dir);
if sources.is_empty() {
return Err("the manifest names no usable logo".into());
}
(png_icon(&sources, big)?, png_icon(&sources, small)?)
}
};
BIG.store(big_icon, Ordering::Relaxed);
SMALL.store(small_icon, Ordering::Relaxed);
unsafe {
wm::PostMessageW(hwnd, wm::WM_SETICON, wm::ICON_BIG as WPARAM, big_icon);
wm::PostMessageW(hwnd, wm::WM_SETICON, wm::ICON_SMALL as WPARAM, small_icon);
}
tracing::info!(big, small, dpi, "icon set");
Ok(())
}
fn load_ico(path: &Path, size: u32) -> Result<isize, String> {
use std::os::windows::ffi::OsStrExt;
let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
let icon = unsafe {
wm::LoadImageW(
std::ptr::null_mut(),
wide.as_ptr(),
wm::IMAGE_ICON,
size as i32,
size as i32,
wm::LR_LOADFROMFILE,
)
};
if icon.is_null() { Err("the .ico file did not load".into()) } else { Ok(icon as isize) }
}
fn png_icon(sources: &[(u32, PathBuf)], size: u32) -> Result<isize, String> {
let sizes: Vec<u32> = sources.iter().map(|(s, _)| *s).collect();
let (_, path) = &sources[pick_source(&sizes, size).ok_or("no source")?];
let pixels = decode(path, size).map_err(|e| format!("{}: {e}", path.display()))?;
make_icon(&pixels, size)
}
fn decode(path: &Path, size: u32) -> windows::core::Result<Vec<u8>> {
use std::os::windows::ffi::OsStrExt;
let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
unsafe {
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
let factory: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
let decoder = factory.CreateDecoderFromFilename(
PCWSTR(wide.as_ptr()),
None,
GENERIC_READ,
WICDecodeMetadataCacheOnDemand,
)?;
let frame = decoder.GetFrame(0)?;
let to_pre = factory.CreateFormatConverter()?;
to_pre.Initialize(
&frame,
&GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
None::<&IWICPalette>,
0.0,
WICBitmapPaletteTypeCustom,
)?;
let scaler = factory.CreateBitmapScaler()?;
scaler.Initialize(&to_pre, size, size, WICBitmapInterpolationModeFant)?;
let to_straight = factory.CreateFormatConverter()?;
to_straight.Initialize(
&scaler,
&GUID_WICPixelFormat32bppBGRA,
WICBitmapDitherTypeNone,
None::<&IWICPalette>,
0.0,
WICBitmapPaletteTypeCustom,
)?;
let source: IWICBitmapSource = to_straight.cast()?;
let mut pixels = vec![0u8; (size * size * 4) as usize];
source.CopyPixels(std::ptr::null(), size * 4, &mut pixels)?;
Ok(pixels)
}
}
fn make_icon(bgra: &[u8], size: u32) -> Result<isize, String> {
unsafe {
let mut info: BITMAPINFO = std::mem::zeroed();
info.bmiHeader.biSize = std::mem::size_of_val(&info.bmiHeader) as u32;
info.bmiHeader.biWidth = size as i32;
info.bmiHeader.biHeight = -(size as i32);
info.bmiHeader.biPlanes = 1;
info.bmiHeader.biBitCount = 32;
info.bmiHeader.biCompression = BI_RGB;
let dc = GetDC(std::ptr::null_mut());
let mut bits = std::ptr::null_mut();
let colour = CreateDIBSection(dc, &info, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0);
ReleaseDC(std::ptr::null_mut(), dc);
if colour.is_null() || bits.is_null() {
return Err("no DIB section".into());
}
std::ptr::copy_nonoverlapping(bgra.as_ptr(), bits.cast::<u8>(), bgra.len());
let mask = CreateBitmap(size as i32, size as i32, 1, 1, std::ptr::null());
let icon_info = wm::ICONINFO { fIcon: 1, xHotspot: 0, yHotspot: 0, hbmMask: mask, hbmColor: colour };
let icon = wm::CreateIconIndirect(&icon_info);
DeleteObject(colour);
DeleteObject(mask);
if icon.is_null() { Err("CreateIconIndirect failed".into()) } else { Ok(icon as isize) }
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+653
View File
@@ -0,0 +1,653 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::collections::HashSet;
use std::ffi::c_void;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, OnceLock};
use super::files;
use super::xasync::E_NOTIMPL;
use super::xgameruntime::{HRESULT, S_OK};
use crate::hle::{HleModule};
use crate::hle_export;
const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
const UNSUPPORTED_SCHEME: HRESULT = 0xC00D_36C3_u32 as i32;
const IID_IUNKNOWN: [u8; 16] = guid(0x0000_0000, 0x0000, 0x0000, [0xC0, 0, 0, 0, 0, 0, 0, 0x46]);
const IID_RESOLVER: [u8; 16] = guid(
0xFBE5_A32D,
0xA497,
0x4B61,
[0xBB, 0x85, 0x97, 0xB1, 0xA8, 0x48, 0xA6, 0xE3],
);
const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] {
let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes());
[
a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6],
d[7],
]
}
fn local(url: &[u16]) -> Result<Vec<u16>, (String, String)> {
let text = String::from_utf16_lossy(url);
let drive = |s: &str| {
let b = s.as_bytes();
b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
};
let host_of = |rest: &str| rest.split(['/', '\\']).next().unwrap_or("").to_string();
let share = |s: &str| {
let b = s.as_bytes();
b.len() >= 2 && b[..2].iter().all(|c| b"/\\".contains(c))
};
let path = if let Some(rest) = text.strip_prefix(r"\\?\") {
if !drive(rest) {
return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\"))));
}
text.clone()
} else if let Some(rest) = text.strip_prefix(r"\??\") {
if !drive(rest) {
return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\"))));
}
return Ok(with_nul(url));
} else if share(&text) {
return Err(("unc".into(), host_of(&text[2..])));
} else if drive(&text) {
text.clone()
} else if let Some((scheme, rest)) = text.split_once(':').filter(|(s, _)| {
s.len() > 1
&& s.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"+-.".contains(&c))
}) {
let scheme = scheme.to_ascii_lowercase();
let authority = rest.strip_prefix("//");
if scheme != "file" {
return Err((scheme, authority.map(host_of).unwrap_or_default()));
}
let (path, this_machine) = match authority {
Some(rest) => {
let host = host_of(rest);
if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") {
return Err((scheme, host));
}
(&rest[host.len()..], !host.is_empty())
}
None => (rest, false),
};
let whole = percent_decode(path);
let path = percent_decode(path.trim_start_matches(['/', '\\'])).replace('/', "\\");
if !drive(&path) {
if !this_machine && share(&whole) {
return Err((scheme, host_of(whole.trim_start_matches(['/', '\\']))));
}
return Ok(with_nul(url));
}
path
} else {
return Ok(with_nul(url));
};
let wide: Vec<u16> = path.encode_utf16().collect();
Ok(files::translate(&wide).unwrap_or_else(|| with_nul(&wide)))
}
fn with_nul(s: &[u16]) -> Vec<u16> {
s.iter().copied().chain([0]).collect()
}
fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
let hex = b
.get(i + 1..i + 3)
.filter(|h| h.iter().all(|c| c.is_ascii_hexdigit()))
.and_then(|h| std::str::from_utf8(h).ok());
match (b[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) {
(b'%', Some(v)) => {
out.push(v);
i += 3;
}
(c, _) => {
out.push(c);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
fn units<'a>(s: *const u16) -> &'a [u16] {
let len = (0..).take_while(|&i| unsafe { s.add(i).read() } != 0).count();
unsafe { std::slice::from_raw_parts(s, len) }
}
fn checked(url: *const u16) -> Result<Vec<u16>, HRESULT> {
if url.is_null() {
return Err(E_POINTER);
}
local(units(url)).map_err(|(scheme, host)| {
static REFUSED: Mutex<Option<HashSet<(String, String)>>> = Mutex::new(None);
let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner());
if refused
.get_or_insert_with(HashSet::new)
.insert((scheme.clone(), host.clone()))
{
tracing::warn!(
scheme,
host,
"media: refused a URL that is not a local file"
);
}
UNSUPPORTED_SCHEME
})
}
fn kept(s: Vec<u16>) -> *const u16 {
static KEPT: Mutex<Option<HashSet<Box<[u16]>>>> = Mutex::new(None);
let mut kept = KEPT.lock().unwrap_or_else(|e| e.into_inner());
let kept = kept.get_or_insert_with(HashSet::new);
if let Some(s) = kept.get(&s[..]) {
return s.as_ptr();
}
let s = s.into_boxed_slice();
let ptr = s.as_ptr();
kept.insert(s);
ptr
}
fn file_path(path: *const u16) -> Option<Vec<u16>> {
if path.is_null() {
return None;
}
files::translate(units(path))
}
const PROC_NOT_FOUND: HRESULT = 0x8007_007F_u32 as i32;
macro_rules! host_or_return {
($dll:literal, $name:literal: $ty:ty) => {{
static ADDRESS: OnceLock<Option<usize>> = OnceLock::new();
match *ADDRESS.get_or_init(|| crate::hle::host::function($dll, $name)) {
Some(address) => unsafe { std::mem::transmute::<usize, $ty>(address) },
None => return PROC_NOT_FOUND,
}
}};
}
fn clear(out: *mut Unknown) {
if !out.is_null() {
unsafe { out.write(std::ptr::null_mut()) };
}
}
#[repr(C)]
struct Host {
vtable: *const usize,
}
impl Host {
unsafe fn method<F: Copy>(this: *mut Host, n: usize) -> F {
unsafe { std::mem::transmute_copy(&*(*this).vtable.add(n)) }
}
}
#[repr(C)]
pub struct Resolver {
vtable: &'static Methods,
host: *mut Host,
refs: AtomicU32,
}
type Unknown = *mut c_void;
extern "system" fn beyond<const SLOT: usize>(_: *mut Resolver) -> HRESULT {
tracing::warn!(
slot = format_args!("{SLOT:#x}"),
"source resolver method not implemented"
);
E_NOTIMPL
}
#[repr(C)]
struct Methods {
query_interface:
extern "system" fn(*mut Resolver, *const [u8; 16], *mut *mut c_void) -> HRESULT,
add_ref: extern "system" fn(*mut Resolver) -> u32,
release: extern "system" fn(*mut Resolver) -> u32,
create_from_url: extern "system" fn(
*mut Resolver,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT,
create_from_stream: extern "system" fn(
*mut Resolver,
Unknown,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT,
begin_from_url: extern "system" fn(
*mut Resolver,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT,
end_from_url: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT,
begin_from_stream: extern "system" fn(
*mut Resolver,
Unknown,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT,
end_from_stream: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT,
cancel: extern "system" fn(*mut Resolver, Unknown) -> HRESULT,
spare: [extern "system" fn(*mut Resolver) -> HRESULT; 8],
}
static METHODS: Methods = Methods {
query_interface,
add_ref,
release,
create_from_url,
create_from_stream,
begin_from_url,
end_from_url,
begin_from_stream,
end_from_stream,
cancel,
spare: [
beyond::<0x50>,
beyond::<0x58>,
beyond::<0x60>,
beyond::<0x68>,
beyond::<0x70>,
beyond::<0x78>,
beyond::<0x80>,
beyond::<0x88>,
],
};
fn host(this: *mut Resolver) -> *mut Host {
unsafe { (*this).host }
}
extern "system" fn query_interface(
this: *mut Resolver,
iid: *const [u8; 16],
out: *mut *mut c_void,
) -> HRESULT {
if iid.is_null() || out.is_null() {
return E_POINTER;
}
let iid = unsafe { *iid };
let found = iid == IID_IUNKNOWN || iid == IID_RESOLVER;
unsafe {
out.write(if found {
this.cast()
} else {
std::ptr::null_mut()
})
};
if !found {
return E_NOINTERFACE;
}
add_ref(this);
S_OK
}
extern "system" fn add_ref(this: *mut Resolver) -> u32 {
unsafe { (*this).refs.fetch_add(1, Ordering::Relaxed) + 1 }
}
extern "system" fn release(this: *mut Resolver) -> u32 {
let left = unsafe { (*this).refs.fetch_sub(1, Ordering::AcqRel) } - 1;
if left == 0 {
let proxy = unsafe { Box::from_raw(this) };
let release: extern "system" fn(*mut Host) -> u32 = unsafe { Host::method(proxy.host, 2) };
release(proxy.host);
}
left
}
extern "system" fn create_from_url(
this: *mut Resolver,
url: *const u16,
flags: u32,
props: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let url = match checked(url) {
Ok(url) => url,
Err(error) => {
clear(object);
return error;
}
};
let host = host(this);
let f: extern "system" fn(
*mut Host,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT = unsafe { Host::method(host, 3) };
f(host, url.as_ptr(), flags, props, kind, object)
}
extern "system" fn begin_from_url(
this: *mut Resolver,
url: *const u16,
flags: u32,
props: Unknown,
cookie: *mut Unknown,
callback: Unknown,
state: Unknown,
) -> HRESULT {
let url = match checked(url) {
Ok(url) => kept(url),
Err(error) => {
clear(cookie);
return error;
}
};
let host = host(this);
let f: extern "system" fn(
*mut Host,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT = unsafe { Host::method(host, 5) };
f(host, url, flags, props, cookie, callback, state)
}
extern "system" fn create_from_stream(
this: *mut Resolver,
stream: Unknown,
url: *const u16,
flags: u32,
props: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let host = host(this);
let f: extern "system" fn(
*mut Host,
Unknown,
*const u16,
u32,
Unknown,
*mut u32,
*mut Unknown,
) -> HRESULT = unsafe { Host::method(host, 4) };
f(host, stream, url, flags, props, kind, object)
}
extern "system" fn end_from_url(
this: *mut Resolver,
result: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let host = host(this);
let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT =
unsafe { Host::method(host, 6) };
f(host, result, kind, object)
}
#[allow(clippy::too_many_arguments)]
extern "system" fn begin_from_stream(
this: *mut Resolver,
stream: Unknown,
url: *const u16,
flags: u32,
props: Unknown,
cookie: *mut Unknown,
callback: Unknown,
state: Unknown,
) -> HRESULT {
let host = host(this);
let f: extern "system" fn(
*mut Host,
Unknown,
*const u16,
u32,
Unknown,
*mut Unknown,
Unknown,
Unknown,
) -> HRESULT = unsafe { Host::method(host, 7) };
f(host, stream, url, flags, props, cookie, callback, state)
}
extern "system" fn end_from_stream(
this: *mut Resolver,
result: Unknown,
kind: *mut u32,
object: *mut Unknown,
) -> HRESULT {
let host = host(this);
let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT =
unsafe { Host::method(host, 8) };
f(host, result, kind, object)
}
extern "system" fn cancel(this: *mut Resolver, cookie: Unknown) -> HRESULT {
let host = host(this);
let f: extern "system" fn(*mut Host, Unknown) -> HRESULT = unsafe { Host::method(host, 9) };
f(host, cookie)
}
pub extern "system" fn MFCreateSourceResolver(out: *mut *mut Resolver) -> HRESULT {
if out.is_null() {
return E_POINTER;
}
static CREATE: OnceLock<Option<usize>> = OnceLock::new();
let Some(create) =
*CREATE.get_or_init(|| crate::hle::host::function("mfplat.dll", "MFCreateSourceResolver"))
else {
return UNSUPPORTED_SCHEME;
};
let create: extern "system" fn(*mut *mut Host) -> HRESULT =
unsafe { std::mem::transmute(create) };
let mut host = std::ptr::null_mut();
let hr = create(&mut host);
if hr < 0 || host.is_null() {
return hr;
}
let proxy = Box::new(Resolver {
vtable: &METHODS,
host,
refs: AtomicU32::new(1),
});
unsafe { out.write(Box::into_raw(proxy)) };
S_OK
}
pub extern "system" fn MFCreateSourceReaderFromURL(
url: *const u16,
attributes: Unknown,
reader: *mut Unknown,
) -> HRESULT {
let url = match checked(url) {
Ok(url) => url,
Err(error) => {
clear(reader);
return error;
}
};
let create = host_or_return!("mfreadwrite.dll", "MFCreateSourceReaderFromURL":
extern "system" fn(*const u16, Unknown, *mut Unknown) -> HRESULT);
create(url.as_ptr(), attributes, reader)
}
pub extern "system" fn MFCreateSinkWriterFromURL(
url: *const u16,
stream: Unknown,
attributes: Unknown,
writer: *mut Unknown,
) -> HRESULT {
let create = host_or_return!("mfreadwrite.dll", "MFCreateSinkWriterFromURL":
extern "system" fn(*const u16, Unknown, Unknown, *mut Unknown) -> HRESULT);
if !stream.is_null() {
return create(url, stream, attributes, writer);
}
let url = match checked(url) {
Ok(url) => url,
Err(error) => {
clear(writer);
return error;
}
};
create(url.as_ptr(), stream, attributes, writer)
}
pub extern "system" fn MFCreateFile(
access: u32,
open: u32,
flags: u32,
path: *const u16,
stream: *mut Unknown,
) -> HRESULT {
let create = host_or_return!("mfplat.dll", "MFCreateFile":
extern "system" fn(u32, u32, u32, *const u16, *mut Unknown) -> HRESULT);
let host = file_path(path);
create(
access,
open,
flags,
host.as_ref().map_or(path, |p| p.as_ptr()),
stream,
)
}
pub extern "system" fn MFBeginCreateFile(
access: u32,
open: u32,
flags: u32,
path: *const u16,
callback: Unknown,
state: Unknown,
cookie: *mut Unknown,
) -> HRESULT {
let begin = host_or_return!("mfplat.dll", "MFBeginCreateFile":
extern "system" fn(u32, u32, u32, *const u16, Unknown, Unknown, *mut Unknown) -> HRESULT);
let path = file_path(path).map_or(path, kept);
begin(access, open, flags, path, callback, state, cookie)
}
const UNSUPPORTED_D3D_TYPE: HRESULT = 0xC00D_6D76_u32 as i32;
fn no_gpu_video(call: &'static str) {
static SAID: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if !said.contains(&call) {
said.push(call);
tracing::warn!(
call,
"media: the title asked for video on the GPU, which is not served (its device and textures are not the host's); refused with MF_E_UNSUPPORTED_D3D_TYPE"
);
}
}
pub extern "system" fn MFResetDXGIDeviceManagerX(manager: Unknown, device: Unknown, _token: u32) -> HRESULT {
if manager.is_null() || device.is_null() {
return E_POINTER;
}
no_gpu_video("MFResetDXGIDeviceManagerX");
UNSUPPORTED_D3D_TYPE
}
pub extern "system" fn MFCreateDXGISurfaceBufferX(
iid: *const [u8; 16],
surface: Unknown,
_subresource: u32,
_bottom_up: i32,
buffer: *mut Unknown,
) -> HRESULT {
clear(buffer);
if iid.is_null() || surface.is_null() || buffer.is_null() {
return E_POINTER;
}
no_gpu_video("MFCreateDXGISurfaceBufferX");
UNSUPPORTED_D3D_TYPE
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "media",
dlls: &["mfplat.dll"],
exports: vec![
hle_export!(MFCreateSourceResolver),
hle_export!(MFCreateFile),
hle_export!(MFBeginCreateFile),
hle_export!(MFResetDXGIDeviceManagerX),
hle_export!(MFCreateDXGISurfaceBufferX),
],
}
}
pub(crate) fn readers() -> HleModule {
HleModule {
name: "media readers",
dlls: &["mfreadwrite.dll"],
exports: vec![
hle_export!(MFCreateSourceReaderFromURL),
hle_export!(MFCreateSinkWriterFromURL),
],
}
}
+424
View File
@@ -0,0 +1,424 @@
use super::{
A, B, DOWN, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER,
RIGHT_STICK, UP, VIEW, X, Y,
};
use std::sync::atomic::{AtomicU32, Ordering::Relaxed};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use windows_sys::Win32::{
Foundation::{HWND, POINT, RECT},
UI::{Input::KeyboardAndMouse::GetAsyncKeyState, WindowsAndMessaging as wm},
};
fn is_mouse_button(vk: u8) -> bool {
matches!(vk, 1..=6)
}
static LATCHED: AtomicU32 = AtomicU32::new(0);
fn latched(vk: u8) -> bool {
LATCHED.load(Relaxed) & (1 << vk) != 0
}
pub(crate) fn forget_buttons() {
LATCHED.store(0, Relaxed);
}
pub(crate) fn note_button(message: u32, wparam: usize) -> bool {
let (vk, held) = match message {
wm::WM_LBUTTONDOWN => (1u8, true),
wm::WM_LBUTTONUP => (1u8, false),
wm::WM_RBUTTONDOWN => (2, true),
wm::WM_RBUTTONUP => (2, false),
wm::WM_MBUTTONDOWN => (4, true),
wm::WM_MBUTTONUP => (4, false),
wm::WM_XBUTTONDOWN | wm::WM_XBUTTONUP => {
let which = ((wparam >> 16) & 0xffff) as u16;
(if which == 2 { 6 } else { 5 }, message == wm::WM_XBUTTONDOWN)
}
_ => return false,
};
if held {
LATCHED.fetch_or(1 << vk, Relaxed);
} else {
LATCHED.fetch_and(!(1 << vk), Relaxed);
}
true
}
const BUTTONS: &[(&str, u32)] = &[
("A", A),
("B", B),
("X", X),
("Y", Y),
("LB", LEFT_SHOULDER),
("RB", RIGHT_SHOULDER),
("LS", LEFT_STICK),
("RS", RIGHT_STICK),
("Menu", MENU),
("View", VIEW),
("DpadUp", UP),
("DpadDown", DOWN),
("DpadLeft", LEFT),
("DpadRight", RIGHT),
];
const AXES: [&str; 6] = ["LT", "RT", "MoveLeft", "MoveRight", "MoveDown", "MoveUp"];
const WHEEL_UP: u8 = 0x0E;
const WHEEL_DOWN: u8 = 0x0F;
const WHEEL_DELTA: i32 = 120;
const WHEEL_PULSE_MS: u64 = 70;
const WHEEL_GAP_MS: u64 = 40;
const WHEEL_QUEUE_MAX: usize = 16;
#[derive(Default)]
struct Wheel {
rest: i32,
queue: std::collections::VecDeque<u8>,
now: Option<(u8, u64)>,
free_at: u64,
}
impl Wheel {
fn scroll(&mut self, delta: i32) {
if delta != 0 && self.rest != 0 && (delta < 0) != (self.rest < 0) {
self.rest = 0;
}
self.rest = self.rest.saturating_add(delta);
let key = if self.rest > 0 { WHEEL_UP } else { WHEEL_DOWN };
let n = (self.rest / WHEEL_DELTA).unsigned_abs() as usize;
self.rest %= WHEEL_DELTA;
for _ in 0..n {
if self.queue.len() < WHEEL_QUEUE_MAX {
self.queue.push_back(key);
}
}
}
fn poll(&mut self, ms: u64) -> Option<u8> {
if let Some((key, until)) = self.now {
if ms < until {
return Some(key);
}
self.now = None;
self.free_at = until + WHEEL_GAP_MS;
}
if ms >= self.free_at
&& let Some(key) = self.queue.pop_front()
{
self.now = Some((key, ms + WHEEL_PULSE_MS));
return Some(key);
}
None
}
}
fn wheel() -> std::sync::MutexGuard<'static, Wheel> {
static WHEEL: OnceLock<Mutex<Wheel>> = OnceLock::new();
WHEEL
.get_or_init(Default::default)
.lock()
.unwrap_or_else(|e| e.into_inner())
}
pub(crate) fn wheel_scroll(hwnd: HWND, delta: i32) {
if enabled()
&& !eonacat_xsbox_gpu::SETTINGS_MENU_OPEN.load(Relaxed)
&& unsafe { wm::GetForegroundWindow() } == hwnd
{
wheel().scroll(delta);
}
}
struct Bindings {
buttons: Vec<(u8, u32)>,
axes: [Vec<u8>; 6],
sensitivity: f32,
}
fn key(name: &str) -> Option<u8> {
let name = name.trim().to_ascii_uppercase();
if name.len() == 1 && name.as_bytes()[0].is_ascii_alphanumeric() {
return Some(name.as_bytes()[0]);
}
if let Some(hex) = name.strip_prefix("0X") {
return u8::from_str_radix(hex, 16)
.ok()
.filter(|v| *v > 0 && *v < 255);
}
Some(match name.as_str() {
"MOUSE1" => 1,
"MOUSE2" => 2,
"MOUSE3" => 4,
"MOUSE4" => 5,
"MOUSE5" => 6,
"WHEELUP" => WHEEL_UP,
"WHEELDOWN" => WHEEL_DOWN,
"BACKSPACE" => 8,
"TAB" => 9,
"ENTER" => 13,
"SHIFT" => 16,
"CTRL" => 17,
"ALT" => 18,
"ESC" => 27,
"SPACE" => 32,
"LEFT" => 37,
"UP" => 38,
"RIGHT" => 39,
"DOWN" => 40,
_ => return None,
})
}
fn parse(file: &str) -> Result<Bindings, String> {
let mut b = Bindings {
buttons: Vec::new(),
axes: Default::default(),
sensitivity: 0.045,
};
for (i, line) in file.lines().enumerate() {
let line = line.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
let err = || format!("Invalid binding on line {}: {}", i + 1, line);
let (out, input) = line.split_once('=').ok_or_else(err)?;
let out = out.trim();
if out.eq_ignore_ascii_case("Sensitivity") {
b.sensitivity = input
.trim()
.parse::<f32>()
.ok()
.filter(|s| s.is_finite() && *s > 0.0)
.ok_or_else(err)?;
continue;
}
let keys = input
.split(',')
.map(|k| key(k).ok_or_else(err))
.collect::<Result<Vec<_>, _>>()?;
if let Some((_, bit)) = BUTTONS
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(out))
{
b.buttons.extend(keys.into_iter().map(|k| (k, *bit)));
} else {
let index = AXES
.iter()
.position(|s| s.eq_ignore_ascii_case(out))
.ok_or_else(err)?;
b.axes[index].extend(keys);
}
}
Ok(b)
}
fn load() -> Option<Bindings> {
let file = std::env::var_os("EONACAT_XS_MNK_BINDINGS")?;
match std::fs::read_to_string(file)
.map_err(|e| e.to_string())
.and_then(|s| parse(&s))
{
Ok(b) => Some(b),
Err(e) => {
eprintln!("Mouse and keyboard disabled: {e}");
None
}
}
}
fn config() -> Option<Arc<Bindings>> {
static CONFIG: Mutex<(u32, Option<Option<Arc<Bindings>>>)> = Mutex::new((0, None));
let changed = eonacat_xsbox_gpu::MNK_BINDINGS_CHANGED.load(Relaxed);
let mut c = CONFIG.lock().unwrap_or_else(|e| e.into_inner());
refresh(&mut c, changed, load)
}
fn refresh<B>(state: &mut (u32, Option<Option<Arc<B>>>), changed: u32, load: impl FnOnce() -> Option<B>) -> Option<Arc<B>> {
match &state.1 {
None => *state = (changed, Some(load().map(Arc::new))),
Some(_) if state.0 != changed => {
state.0 = changed;
if let Some(b) = load() {
state.1 = Some(Some(Arc::new(b)));
}
}
_ => {}
}
state.1.clone().flatten()
}
pub(crate) fn bound_buttons() -> Option<Vec<(u8, u32)>> {
config().map(|b| b.buttons.clone())
}
pub(crate) fn enabled() -> bool {
config().is_some()
}
#[derive(Default)]
struct Mouse {
window: usize,
velocity: [f32; 2],
stick: [f32; 2],
last: Option<Instant>,
last_motion: Option<Instant>,
centered: bool,
}
fn mouse() -> std::sync::MutexGuard<'static, Mouse> {
static STATE: OnceLock<Mutex<Mouse>> = OnceLock::new();
STATE.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
}
fn recenter(hwnd: HWND, centered: bool) -> Option<[i32; 2]> {
if crate::hle::modules::lifecycle::mouse_dragging() {
return None;
}
let mut rect = RECT::default();
let mut cursor = POINT::default();
unsafe {
if wm::GetClientRect(hwnd, &mut rect) == 0 || rect.right <= 0 || rect.bottom <= 0 {
return None;
}
let mut top_left = POINT { x: 0, y: 0 };
let mut bottom_right = POINT {
x: rect.right,
y: rect.bottom,
};
if windows_sys::Win32::Graphics::Gdi::ClientToScreen(hwnd, &mut top_left) == 0
|| windows_sys::Win32::Graphics::Gdi::ClientToScreen(hwnd, &mut bottom_right) == 0
|| wm::GetCursorPos(&mut cursor) == 0
|| wm::GetForegroundWindow() != hwnd
{
return None;
}
if !centered
&& (cursor.x < top_left.x
|| cursor.x >= bottom_right.x
|| cursor.y < top_left.y
|| cursor.y >= bottom_right.y)
{
return None;
}
let center = POINT {
x: top_left.x + (bottom_right.x - top_left.x) / 2,
y: top_left.y + (bottom_right.y - top_left.y) / 2,
};
let delta = [cursor.x - center.x, cursor.y - center.y];
if delta != [0, 0] && wm::SetCursorPos(center.x, center.y) == 0 {
return None;
}
Some(delta)
}
}
impl Mouse {
fn update_look(&mut self, delta: [i32; 2], now: Instant, elapsed: Duration, sensitivity: f32) {
if delta != [0, 0] {
self.last_motion = Some(now);
}
if self
.last_motion
.is_none_or(|t| now.duration_since(t) >= Duration::from_millis(40))
{
self.velocity = [0.0; 2];
self.stick = [0.0; 2];
return;
}
let seconds = elapsed.as_secs_f32();
let weight = 1.0 - (-seconds / 0.020).exp();
for (v, d) in self
.velocity
.iter_mut()
.zip([delta[0] as f32, -(delta[1] as f32)])
{
let target = d * sensitivity * 0.008 / seconds;
*v += weight * (target - *v);
}
let length = self.velocity[0].hypot(self.velocity[1]);
if length <= 0.001 {
self.stick = [0.0; 2];
} else {
let gain = (0.24 + 0.76 * length.min(1.0)) / length;
self.stick = self.velocity.map(|v| v * gain);
}
}
}
pub(super) fn sample() -> Option<PadState> {
let b = config()?;
let mut m = mouse();
if eonacat_xsbox_gpu::SETTINGS_MENU_OPEN.load(Relaxed) || crate::hle::modules::lifecycle::mouse_dragging() {
*m = Mouse::default();
*wheel() = Wheel::default();
return Some(PadState::default());
}
let hwnd = unsafe { wm::GetForegroundWindow() };
let mut pid = 0;
unsafe { wm::GetWindowThreadProcessId(hwnd, &mut pid) };
if hwnd.is_null() || pid != std::process::id() {
*m = Mouse::default();
*wheel() = Wheel::default();
return Some(PadState::default());
}
if m.window != hwnd as usize {
*m = Mouse {
window: hwnd as usize,
..Default::default()
};
}
let now = Instant::now();
let elapsed = m
.last
.map_or(Duration::from_millis(8), |last| now.duration_since(last));
if elapsed >= Duration::from_millis(8) {
let displacement = recenter(hwnd, m.centered);
let delta = if m.centered {
displacement.unwrap_or_default()
} else {
[0, 0]
};
m.centered = displacement.is_some();
m.update_look(delta, now, elapsed, b.sensitivity);
m.last = Some(now);
}
static START: OnceLock<Instant> = OnceLock::new();
let ms = now.duration_since(*START.get_or_init(|| now)).as_millis() as u64;
let wheel_key = wheel().poll(ms);
let held = |vk: u8| match vk {
WHEEL_UP | WHEEL_DOWN => wheel_key == Some(vk),
_ => {
let down = (unsafe { GetAsyncKeyState(vk.into()) }) < 0;
if is_mouse_button(vk) { down || latched(vk) } else { down }
}
};
let axes = b
.axes
.each_ref()
.map(|keys| u8::from(keys.iter().copied().any(held)) as f32);
Some(PadState {
buttons: b
.buttons
.iter()
.filter(|(vk, _)| held(*vk))
.fold(0, |v, (_, bit)| v | bit),
left_trigger: axes[0],
right_trigger: axes[1],
left_x: axes[3] - axes[2],
left_y: axes[5] - axes[4],
right_x: m.stick[0],
right_y: m.stick[1],
})
}
+90
View File
@@ -0,0 +1,90 @@
#[cfg(windows)]
pub mod apu;
pub mod audio;
pub mod bink;
pub mod d3d12x;
pub mod display;
pub mod dsp;
#[cfg(windows)]
pub mod dstorage;
#[cfg(windows)]
pub mod fidelityfx;
#[cfg(windows)]
pub mod files;
pub mod gameinput;
#[cfg(windows)]
pub mod icon;
pub mod kernel;
#[cfg(windows)]
pub mod lifecycle;
#[cfg(windows)]
pub mod media;
#[cfg(windows)]
pub mod net;
pub mod rpcrt4;
pub mod speech;
#[cfg(windows)]
pub mod theme;
pub mod storage;
pub mod xasync;
#[cfg(windows)]
pub mod xboxbvh;
pub mod xg;
#[cfg(windows)]
pub mod xaudio2;
pub mod xcurl;
pub mod xgame;
pub mod xgameruntime;
pub mod xgamesave;
pub mod xgameui;
#[cfg(windows)]
pub mod xmem;
pub mod xnetworking;
pub mod xpackage;
pub mod xstore;
pub mod xsystem;
pub mod xuser;
use crate::hle::HleModule;
pub(crate) fn all() -> Vec<HleModule> {
let mut all = vec![
kernel::module(),
xgameruntime::module(),
gameinput::module(),
d3d12x::module(),
audio::module(),
dsp::module(),
xg::module(),
];
#[cfg(windows)]
all.push(apu::module());
#[cfg(windows)]
all.push(media::module());
#[cfg(windows)]
all.push(media::readers());
#[cfg(windows)]
all.push(xaudio2::module());
all.push(xcurl::module());
#[cfg(windows)]
all.push(dstorage::module());
#[cfg(windows)]
all.push(files::module());
#[cfg(windows)]
all.push(lifecycle::module());
#[cfg(windows)]
all.push(net::module());
all.push(rpcrt4::module());
#[cfg(windows)]
all.push(xmem::module());
#[cfg(windows)]
all.push(xsystem::module());
#[cfg(windows)]
if eonacat_xsbox_gpu::hwrt::requested() {
all.push(xboxbvh::module());
}
all
}
+848
View File
@@ -0,0 +1,848 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
#![allow(clippy::too_many_arguments)]
use std::ffi::{CStr, c_char, c_void};
use std::net::{IpAddr, SocketAddr};
use std::sync::Mutex;
use windows_sys::Win32::Foundation::SetLastError;
use crate::hle::modules::files::host;
use crate::hle::{HleExport, HleModule};
use crate::hle_export;
const SOCKET_ERROR: i32 = -1;
const INVALID_SOCKET: Socket = !0;
const WSAEINVAL: i32 = 10022;
const WSAEADDRNOTAVAIL: i32 = 10049;
const WSAENETUNREACH: i32 = 10051;
const WSASERVICE_NOT_FOUND: i32 = 10108;
const WSAHOST_NOT_FOUND: i32 = 11001;
const ERROR_WINHTTP_CANNOT_CONNECT: u32 = 12029;
const ERROR_WINHTTP_AUTODETECTION_FAILED: u32 = 12180;
const AF_INET: u16 = 2;
const AF_INET6: u16 = 23;
const NI_NUMERICHOST: i32 = 0x02;
const NI_NAMEREQD: i32 = 0x04;
const SIO_GET_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0006;
const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0024;
const WINHTTP_ACCESS_TYPE_NO_PROXY: u32 = 1;
const WINHTTP_OPTION_PROXY: u32 = 38;
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq)]
struct Guid(u32, u16, u16, [u8; 8]);
const WSAID_CONNECTEX: Guid = Guid(
0x25a2_07b9,
0xddf3,
0x4660,
[0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e],
);
const WSAID_WSASENDMSG: Guid = Guid(
0xa441_e712,
0x754f,
0x43ca,
[0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d],
);
type Socket = usize;
type Handle = *mut c_void;
fn once(what: &'static str, destination: String) {
let own = ["COMPUTERNAME", "USERDOMAIN"]
.iter()
.filter_map(|name| std::env::var(name).ok())
.any(|name| name.eq_ignore_ascii_case(&destination));
let destination = if own { "<pc>".to_owned() } else { destination };
static SEEN: Mutex<Vec<(&str, String)>> = Mutex::new(Vec::new());
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
if !seen.iter().any(|(w, d)| *w == what && *d == destination) {
tracing::info!(%destination, "{what}");
seen.push((what, destination));
}
}
fn wsa_error(code: i32) {
host!("ws2_32.dll", "WSASetLastError": extern "system" fn(i32))(code);
}
fn narrow(text: *const c_char) -> Option<String> {
(!text.is_null()).then(|| {
unsafe { CStr::from_ptr(text) }
.to_string_lossy()
.into_owned()
})
}
fn wide(text: *const u16) -> Option<String> {
(!text.is_null()).then(|| unsafe {
let len = (0..).take_while(|&i| *text.add(i) != 0).count();
String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
})
}
fn socket_addr(addr: *const u8, len: i32) -> Option<SocketAddr> {
let len = usize::try_from(len).ok()?;
if addr.is_null() || len < 4 {
return None;
}
let b = unsafe { std::slice::from_raw_parts(addr, len) };
let port = u16::from_be_bytes([b[2], b[3]]);
match u16::from_le_bytes([b[0], b[1]]) {
AF_INET if len >= 16 => Some((<[u8; 4]>::try_from(&b[4..8]).ok()?, port).into()),
AF_INET6 if len >= 28 => Some((<[u8; 16]>::try_from(&b[8..24]).ok()?, port).into()),
_ => None,
}
}
fn raw_ip(addr: *const c_char, len: i32, kind: i32) -> Option<IpAddr> {
let len = usize::try_from(len).ok()?;
if addr.is_null() {
return None;
}
let b = unsafe { std::slice::from_raw_parts(addr.cast::<u8>(), len) };
match (u16::try_from(kind).ok()?, len) {
(AF_INET, 4..) => Some(<[u8; 4]>::try_from(&b[..4]).ok()?.into()),
(AF_INET6, 16..) => Some(<[u8; 16]>::try_from(&b[..16]).ok()?.into()),
_ => None,
}
}
fn loopback(ip: IpAddr) -> bool {
ip.to_canonical().is_loopback()
}
fn loopback_name(name: &str) -> bool {
let bare = name.trim_start_matches('[').trim_end_matches(']');
bare.eq_ignore_ascii_case("localhost") || bare.parse().is_ok_and(loopback)
}
fn shown(addr: Option<impl ToString>) -> String {
addr.map_or_else(|| "not an IP address".into(), |a| a.to_string())
}
fn reachable(what: &'static str, addr: *const u8, len: i32) -> bool {
match socket_addr(addr, len) {
Some(a) if loopback(a.ip()) => true,
a => {
once(what, shown(a));
wsa_error(WSAENETUNREACH);
false
}
}
}
fn reachable_name(name: Option<String>) -> bool {
match name {
Some(name) if !loopback_name(&name) => {
let literal = name.parse::<IpAddr>().is_ok();
once("network connect blocked", name);
wsa_error(if literal {
WSAENETUNREACH
} else {
WSAHOST_NOT_FOUND
});
false
}
_ => true,
}
}
fn resolvable(name: Option<String>) -> bool {
match name {
Some(name)
if !(name.is_empty()
|| name.eq_ignore_ascii_case("localhost")
|| name.parse::<IpAddr>().is_ok()) =>
{
once("network name lookup blocked", name);
wsa_error(WSAHOST_NOT_FOUND);
false
}
_ => true,
}
}
fn reverse_resolvable(ip: Option<IpAddr>) -> bool {
match ip {
Some(ip) if loopback(ip) => true,
ip => {
once("network reverse lookup blocked", shown(ip));
false
}
}
}
fn name_info_flags(sa: *const u8, len: i32, host_wanted: bool, flags: i32) -> Option<i32> {
if !host_wanted
|| flags & NI_NUMERICHOST != 0
|| reverse_resolvable(socket_addr(sa, len).map(|a| a.ip()))
{
Some(flags)
} else if flags & NI_NAMEREQD != 0 {
wsa_error(WSAHOST_NOT_FOUND);
None
} else {
Some(flags | NI_NUMERICHOST)
}
}
pub extern "system" fn connect(s: Socket, name: *const u8, len: i32) -> i32 {
if !reachable("network connect blocked", name, len) {
return SOCKET_ERROR;
}
host!("ws2_32.dll", "connect": extern "system" fn(Socket, *const u8, i32) -> i32)(s, name, len)
}
pub extern "system" fn WSAConnect(
s: Socket,
name: *const u8,
len: i32,
caller_data: *const c_void,
callee_data: *mut c_void,
sqos: *const c_void,
gqos: *const c_void,
) -> i32 {
if !reachable("network connect blocked", name, len) {
return SOCKET_ERROR;
}
host!("ws2_32.dll", "WSAConnect": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void) -> i32)(
s,
name,
len,
caller_data,
callee_data,
sqos,
gqos,
)
}
pub extern "system" fn WSAConnectByNameA(
s: Socket,
node: *const c_char,
service: *const c_char,
local_len: *mut u32,
local: *mut c_void,
remote_len: *mut u32,
remote: *mut c_void,
timeout: *const c_void,
reserved: *mut c_void,
) -> i32 {
if !reachable_name(narrow(node)) {
return 0;
}
host!("ws2_32.dll", "WSAConnectByNameA": extern "system" fn(Socket, *const c_char, *const c_char, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)(
s, node, service, local_len, local, remote_len, remote, timeout, reserved,
)
}
pub extern "system" fn WSAConnectByNameW(
s: Socket,
node: *const u16,
service: *const u16,
local_len: *mut u32,
local: *mut c_void,
remote_len: *mut u32,
remote: *mut c_void,
timeout: *const c_void,
reserved: *mut c_void,
) -> i32 {
if !reachable_name(wide(node)) {
return 0;
}
host!("ws2_32.dll", "WSAConnectByNameW": extern "system" fn(Socket, *const u16, *const u16, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)(
s, node, service, local_len, local, remote_len, remote, timeout, reserved,
)
}
#[repr(C)]
struct SocketAddress {
addr: *const u8,
len: i32,
}
pub extern "system" fn WSAConnectByList(
s: Socket,
list: *const u8,
local_len: *mut u32,
local: *mut c_void,
remote_len: *mut u32,
remote: *mut c_void,
timeout: *const c_void,
reserved: *mut c_void,
) -> i32 {
if !list.is_null() {
let entries = unsafe {
let count = usize::try_from(list.cast::<i32>().read()).unwrap_or(0);
std::slice::from_raw_parts(list.add(8).cast::<SocketAddress>(), count)
};
if !entries
.iter()
.all(|e| reachable("network connect blocked", e.addr, e.len))
{
return 0;
}
}
host!("ws2_32.dll", "WSAConnectByList": extern "system" fn(Socket, *const u8, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)(
s, list, local_len, local, remote_len, remote, timeout, reserved,
)
}
pub extern "system" fn WSAJoinLeaf(
s: Socket,
name: *const u8,
len: i32,
caller_data: *const c_void,
callee_data: *mut c_void,
sqos: *const c_void,
gqos: *const c_void,
flags: u32,
) -> Socket {
if !reachable("network connect blocked", name, len) {
return INVALID_SOCKET;
}
host!("ws2_32.dll", "WSAJoinLeaf": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void, u32) -> Socket)(
s,
name,
len,
caller_data,
callee_data,
sqos,
gqos,
flags,
)
}
extern "system" fn connect_ex(
s: Socket,
name: *const u8,
len: i32,
send: *const c_void,
send_len: u32,
sent: *mut u32,
overlapped: *mut c_void,
) -> i32 {
if !reachable("network connect blocked", name, len) {
return 0;
}
let (mut real, mut size) = (0usize, 0u32);
let ioctl = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32);
let guid = WSAID_CONNECTEX;
let found = ioctl(
s,
SIO_GET_EXTENSION_FUNCTION_POINTER,
(&raw const guid).cast(),
16,
(&raw mut real).cast(),
8,
&mut size,
std::ptr::null_mut(),
std::ptr::null(),
);
if found != 0 {
return 0;
}
if real == 0 {
const WSAEINVAL: i32 = 10022;
wsa_error(WSAEINVAL);
return 0;
}
let real = unsafe {
std::mem::transmute::<
usize,
extern "system" fn(
Socket,
*const u8,
i32,
*const c_void,
u32,
*mut u32,
*mut c_void,
) -> i32,
>(real)
};
real(s, name, len, send, send_len, sent, overlapped)
}
pub extern "system" fn WSAIoctl(
s: Socket,
code: u32,
input: *const c_void,
input_len: u32,
output: *mut c_void,
output_len: u32,
returned: *mut u32,
overlapped: *mut c_void,
completion: *const c_void,
) -> i32 {
if code == SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER {
wsa_error(WSAEINVAL);
return SOCKET_ERROR;
}
let result = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)(
s, code, input, input_len, output, output_len, returned, overlapped, completion,
);
if result == 0 && code == SIO_GET_EXTENSION_FUNCTION_POINTER && input_len >= 16 {
unsafe {
let ours = match input.cast::<Guid>().read_unaligned() {
WSAID_CONNECTEX => connect_ex as *const () as usize,
WSAID_WSASENDMSG => WSASendMsg as *const () as usize,
_ => return result,
};
output.cast::<usize>().write_unaligned(ours);
}
}
result
}
pub extern "system" fn sendto(
s: Socket,
buf: *const u8,
len: i32,
flags: i32,
to: *const u8,
to_len: i32,
) -> i32 {
if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) {
return SOCKET_ERROR;
}
host!("ws2_32.dll", "sendto": extern "system" fn(Socket, *const u8, i32, i32, *const u8, i32) -> i32)(
s, buf, len, flags, to, to_len,
)
}
pub extern "system" fn WSASendTo(
s: Socket,
buffers: *const c_void,
count: u32,
sent: *mut u32,
flags: u32,
to: *const u8,
to_len: i32,
overlapped: *mut c_void,
completion: *const c_void,
) -> i32 {
if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) {
return SOCKET_ERROR;
}
host!("ws2_32.dll", "WSASendTo": extern "system" fn(Socket, *const c_void, u32, *mut u32, u32, *const u8, i32, *mut c_void, *const c_void) -> i32)(
s, buffers, count, sent, flags, to, to_len, overlapped, completion,
)
}
fn stream(s: Socket) -> bool {
const SOL_SOCKET: i32 = 0xffff;
const SO_TYPE: i32 = 0x1008;
const SOCK_STREAM: i32 = 1;
let (mut kind, mut len) = (0i32, 4i32);
let getsockopt = host!("ws2_32.dll", "getsockopt": extern "system" fn(Socket, i32, i32, *mut i32, *mut i32) -> i32);
getsockopt(s, SOL_SOCKET, SO_TYPE, &mut kind, &mut len) == 0 && kind == SOCK_STREAM
}
#[repr(C)]
struct MessageName {
name: *const u8,
len: i32,
}
pub extern "system" fn WSASendMsg(
s: Socket,
message: *const c_void,
flags: u32,
sent: *mut u32,
overlapped: *mut c_void,
completion: *const c_void,
) -> i32 {
if let Some(m) = unsafe { message.cast::<MessageName>().as_ref() }
&& !m.name.is_null()
&& !reachable("network datagram blocked", m.name, m.len)
{
return SOCKET_ERROR;
}
host!("ws2_32.dll", "WSASendMsg": extern "system" fn(Socket, *const c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)(
s, message, flags, sent, overlapped, completion,
)
}
fn dual_stack(s: Socket) -> bool {
const IPPROTO_IPV6: i32 = 41;
const IPV6_V6ONLY: i32 = 27;
let get = host!("ws2_32.dll", "getsockopt": extern "system" fn(Socket, i32, i32, *mut u8, *mut i32) -> i32);
let (mut only, mut size) = (1u32, 4i32);
get(s, IPPROTO_IPV6, IPV6_V6ONLY, (&raw mut only).cast(), &mut size) == 0 && only == 0
}
pub extern "system" fn bind(s: Socket, name: *const u8, len: i32) -> i32 {
let host_bind = host!("ws2_32.dll", "bind": extern "system" fn(Socket, *const u8, i32) -> i32);
match socket_addr(name, len) {
Some(a) if loopback(a.ip()) => host_bind(s, name, len),
Some(a) if a.ip().is_unspecified() => {
once("network bind narrowed to loopback", a.to_string());
let mut local = unsafe { std::slice::from_raw_parts(name, len as usize) }.to_vec();
match a {
SocketAddr::V4(_) => local[4..8].copy_from_slice(&[127, 0, 0, 1]),
SocketAddr::V6(_) if dual_stack(s) => {
local[8..24].copy_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1]);
}
SocketAddr::V6(_) => local[23] = 1,
}
host_bind(s, local.as_ptr(), len)
}
a => {
once("network bind blocked", shown(a));
wsa_error(WSAEADDRNOTAVAIL);
SOCKET_ERROR
}
}
}
fn blocked_lookup(result: *mut *mut c_void) -> i32 {
if !result.is_null() {
unsafe { result.write(std::ptr::null_mut()) };
}
WSAHOST_NOT_FOUND
}
pub extern "system" fn getaddrinfo(
node: *const c_char,
service: *const c_char,
hints: *const c_void,
result: *mut *mut c_void,
) -> i32 {
if !resolvable(narrow(node)) {
return blocked_lookup(result);
}
host!("ws2_32.dll", "getaddrinfo": extern "system" fn(*const c_char, *const c_char, *const c_void, *mut *mut c_void) -> i32)(
node, service, hints, result,
)
}
pub extern "system" fn GetAddrInfoW(
node: *const u16,
service: *const u16,
hints: *const c_void,
result: *mut *mut c_void,
) -> i32 {
if !resolvable(wide(node)) {
return blocked_lookup(result);
}
host!("ws2_32.dll", "GetAddrInfoW": extern "system" fn(*const u16, *const u16, *const c_void, *mut *mut c_void) -> i32)(
node, service, hints, result,
)
}
pub extern "system" fn GetAddrInfoExA(
name: *const c_char,
service: *const c_char,
namespace: u32,
provider: *const c_void,
hints: *const c_void,
result: *mut *mut c_void,
timeout: *const c_void,
overlapped: *mut c_void,
completion: *const c_void,
handle: *mut Handle,
) -> i32 {
if !resolvable(narrow(name)) {
return blocked_lookup(result);
}
host!("ws2_32.dll", "GetAddrInfoExA": extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)(
name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle,
)
}
pub extern "system" fn GetAddrInfoExW(
name: *const u16,
service: *const u16,
namespace: u32,
provider: *const c_void,
hints: *const c_void,
result: *mut *mut c_void,
timeout: *const c_void,
overlapped: *mut c_void,
completion: *const c_void,
handle: *mut Handle,
) -> i32 {
if !resolvable(wide(name)) {
return blocked_lookup(result);
}
host!("ws2_32.dll", "GetAddrInfoExW": extern "system" fn(*const u16, *const u16, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)(
name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle,
)
}
pub extern "system" fn gethostbyname(name: *const c_char) -> *mut c_void {
if !resolvable(narrow(name)) {
return std::ptr::null_mut();
}
host!("ws2_32.dll", "gethostbyname": extern "system" fn(*const c_char) -> *mut c_void)(name)
}
pub extern "system" fn WSAAsyncGetHostByName(
window: Handle,
message: u32,
name: *const c_char,
buf: *mut c_char,
buf_len: i32,
) -> Handle {
if !resolvable(narrow(name)) {
return std::ptr::null_mut();
}
host!("ws2_32.dll", "WSAAsyncGetHostByName": extern "system" fn(Handle, u32, *const c_char, *mut c_char, i32) -> Handle)(
window, message, name, buf, buf_len,
)
}
pub extern "system" fn WSALookupServiceBeginA(
_restrictions: *const c_void,
_flags: u32,
_lookup: *mut Handle,
) -> i32 {
once("network name-space query blocked", "any".into());
wsa_error(WSASERVICE_NOT_FOUND);
SOCKET_ERROR
}
pub extern "system" fn WSALookupServiceBeginW(
restrictions: *const c_void,
flags: u32,
lookup: *mut Handle,
) -> i32 {
WSALookupServiceBeginA(restrictions, flags, lookup)
}
pub extern "system" fn gethostbyaddr(addr: *const c_char, len: i32, kind: i32) -> *mut c_void {
if !reverse_resolvable(raw_ip(addr, len, kind)) {
wsa_error(WSAHOST_NOT_FOUND);
return std::ptr::null_mut();
}
host!("ws2_32.dll", "gethostbyaddr": extern "system" fn(*const c_char, i32, i32) -> *mut c_void)(
addr, len, kind,
)
}
pub extern "system" fn WSAAsyncGetHostByAddr(
window: Handle,
message: u32,
addr: *const c_char,
len: i32,
kind: i32,
buf: *mut c_char,
buf_len: i32,
) -> Handle {
if !reverse_resolvable(raw_ip(addr, len, kind)) {
wsa_error(WSAHOST_NOT_FOUND);
return std::ptr::null_mut();
}
host!("ws2_32.dll", "WSAAsyncGetHostByAddr": extern "system" fn(Handle, u32, *const c_char, i32, i32, *mut c_char, i32) -> Handle)(
window, message, addr, len, kind, buf, buf_len,
)
}
pub extern "system" fn getnameinfo(
sa: *const u8,
sa_len: i32,
host: *mut c_char,
host_len: u32,
serv: *mut c_char,
serv_len: u32,
flags: i32,
) -> i32 {
let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else {
return WSAHOST_NOT_FOUND;
};
host!("ws2_32.dll", "getnameinfo": extern "system" fn(*const u8, i32, *mut c_char, u32, *mut c_char, u32, i32) -> i32)(
sa, sa_len, host, host_len, serv, serv_len, flags,
)
}
pub extern "system" fn GetNameInfoW(
sa: *const u8,
sa_len: i32,
host: *mut u16,
host_len: u32,
serv: *mut u16,
serv_len: u32,
flags: i32,
) -> i32 {
let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else {
return WSAHOST_NOT_FOUND;
};
host!("ws2_32.dll", "GetNameInfoW": extern "system" fn(*const u8, i32, *mut u16, u32, *mut u16, u32, i32) -> i32)(
sa, sa_len, host, host_len, serv, serv_len, flags,
)
}
pub extern "system" fn WinHttpConnect(
session: Handle,
server: *const u16,
port: u16,
reserved: u32,
) -> Handle {
if let Some(name) = wide(server)
&& !loopback_name(&name)
{
once("HTTP connection blocked", format!("{name}:{port}"));
unsafe { SetLastError(ERROR_WINHTTP_CANNOT_CONNECT) };
return std::ptr::null_mut();
}
host!("winhttp.dll", "WinHttpConnect": extern "system" fn(Handle, *const u16, u16, u32) -> Handle)(
session, server, port, reserved,
)
}
pub extern "system" fn WinHttpOpen(
agent: *const u16,
access: u32,
_proxy: *const u16,
_bypass: *const u16,
flags: u32,
) -> Handle {
if access != WINHTTP_ACCESS_TYPE_NO_PROXY {
once("HTTP proxy ignored", format!("access type {access}"));
}
host!("winhttp.dll", "WinHttpOpen": extern "system" fn(*const u16, u32, *const u16, *const u16, u32) -> Handle)(
agent,
WINHTTP_ACCESS_TYPE_NO_PROXY,
std::ptr::null(),
std::ptr::null(),
flags,
)
}
pub extern "system" fn WinHttpSetOption(
handle: Handle,
option: u32,
buffer: *const c_void,
len: u32,
) -> i32 {
if option == WINHTTP_OPTION_PROXY {
once("HTTP proxy ignored", "WINHTTP_OPTION_PROXY".into());
return 1;
}
host!("winhttp.dll", "WinHttpSetOption": extern "system" fn(Handle, u32, *const c_void, u32) -> i32)(
handle, option, buffer, len,
)
}
fn no_auto_proxy() -> u32 {
once("HTTP proxy auto-detection blocked", "WPAD/PAC".into());
ERROR_WINHTTP_AUTODETECTION_FAILED
}
pub extern "system" fn WinHttpDetectAutoProxyConfigUrl(_flags: u32, _url: *mut *mut u16) -> i32 {
unsafe { SetLastError(no_auto_proxy()) };
0
}
pub extern "system" fn WinHttpGetProxyForUrl(
_session: Handle,
_url: *const u16,
_options: *const c_void,
_info: *mut c_void,
) -> i32 {
unsafe { SetLastError(no_auto_proxy()) };
0
}
pub extern "system" fn WinHttpGetProxyForUrlEx(
_resolver: Handle,
_url: *const u16,
_options: *const c_void,
_context: usize,
) -> u32 {
no_auto_proxy()
}
pub extern "system" fn WinHttpGetProxyForUrlEx2(
_resolver: Handle,
_url: *const u16,
_options: *const c_void,
_selection_len: u32,
_selection: *const u8,
_context: usize,
) -> u32 {
no_auto_proxy()
}
pub extern "system" fn WinHttpGetProxySettingsEx(
_resolver: Handle,
_kind: i32,
_params: *const c_void,
_context: usize,
) -> u32 {
no_auto_proxy()
}
fn ordinal(name: &'static str, f: usize) -> HleExport {
HleExport { name, address: f }
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "net",
dlls: &["ws2_32.dll", "winhttp.dll"],
exports: vec![
hle_export!(connect),
hle_export!(WSAConnect),
hle_export!(WSAConnectByNameA),
hle_export!(WSAConnectByNameW),
hle_export!(WSAConnectByList),
hle_export!(WSAJoinLeaf),
hle_export!(WSAIoctl),
hle_export!(sendto),
hle_export!(WSASendTo),
hle_export!(WSASendMsg),
hle_export!(bind),
hle_export!(getaddrinfo),
hle_export!(GetAddrInfoW),
hle_export!(GetAddrInfoExA),
hle_export!(GetAddrInfoExW),
hle_export!(gethostbyname),
hle_export!(WSAAsyncGetHostByName),
hle_export!(WSALookupServiceBeginA),
hle_export!(WSALookupServiceBeginW),
hle_export!(gethostbyaddr),
hle_export!(WSAAsyncGetHostByAddr),
hle_export!(getnameinfo),
hle_export!(GetNameInfoW),
hle_export!(WinHttpConnect),
hle_export!(WinHttpOpen),
hle_export!(WinHttpSetOption),
hle_export!(WinHttpDetectAutoProxyConfigUrl),
hle_export!(WinHttpGetProxyForUrl),
hle_export!(WinHttpGetProxyForUrlEx),
hle_export!(WinHttpGetProxyForUrlEx2),
hle_export!(WinHttpGetProxySettingsEx),
ordinal("#2", bind as *const () as usize),
ordinal("#4", connect as *const () as usize),
ordinal("#20", sendto as *const () as usize),
ordinal("#51", gethostbyaddr as *const () as usize),
ordinal("#52", gethostbyname as *const () as usize),
ordinal("#102", WSAAsyncGetHostByAddr as *const () as usize),
ordinal("#103", WSAAsyncGetHostByName as *const () as usize),
],
}
}
+283
View File
@@ -0,0 +1,283 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xgameruntime::Guid;
const OK: i32 = 0;
const INVALID_STRING_UUID: i32 = 1705;
const OUT_OF_MEMORY: i32 = 14;
extern "system" fn UuidCreate(uuid: *mut Guid) -> i32 {
create(uuid, false)
}
extern "system" fn UuidCreateSequential(uuid: *mut Guid) -> i32 {
create(uuid, true)
}
fn create(uuid: *mut Guid, _sequential: bool) -> i32 {
if uuid.is_null() {
return INVALID_STRING_UUID;
}
let mut bytes = [0u8; 16];
if !random(&mut bytes) {
return OUT_OF_MEMORY;
}
bytes[7] = (bytes[7] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
unsafe { uuid.write(from_bytes(bytes)) };
OK
}
fn random(bytes: &mut [u8; 16]) -> bool {
#[cfg(windows)]
{
use windows_sys::Win32::Security::Cryptography::{
BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom,
};
let status = unsafe {
BCryptGenRandom(
std::ptr::null_mut(),
bytes.as_mut_ptr(),
bytes.len() as u32,
BCRYPT_USE_SYSTEM_PREFERRED_RNG,
)
};
status >= 0
}
#[cfg(not(windows))]
{
use std::sync::atomic::{AtomicU64, Ordering};
static N: AtomicU64 = AtomicU64::new(0);
let n = N.fetch_add(1, Ordering::Relaxed)
^ std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as u64);
for (i, b) in bytes.iter_mut().enumerate() {
*b = (n >> (8 * (i % 8))) as u8 ^ (i as u8).wrapping_mul(31);
}
true
}
}
extern "system" fn UuidFromStringA(text: *const c_char, uuid: *mut Guid) -> i32 {
if text.is_null() || uuid.is_null() {
return INVALID_STRING_UUID;
}
let bytes = unsafe { std::ffi::CStr::from_ptr(text.cast()) }.to_bytes();
match parse(bytes.iter().copied()) {
Some(g) => unsafe {
uuid.write(g);
OK
},
None => INVALID_STRING_UUID,
}
}
extern "system" fn UuidFromStringW(text: *const u16, uuid: *mut Guid) -> i32 {
if text.is_null() || uuid.is_null() {
return INVALID_STRING_UUID;
}
let mut units = Vec::new();
unsafe {
let mut at = text;
while *at != 0 {
units.push(*at);
at = at.add(1);
}
}
match parse(units.into_iter().map(|u| u as u32)) {
Some(g) => unsafe {
uuid.write(g);
OK
},
None => INVALID_STRING_UUID,
}
}
extern "system" fn UuidToStringA(uuid: *const Guid, out: *mut *mut c_char) -> i32 {
let Some(g) = (unsafe { uuid.as_ref() }) else {
return INVALID_STRING_UUID;
};
if out.is_null() {
return INVALID_STRING_UUID;
}
let text = format(g);
let mut bytes = Vec::with_capacity(37);
bytes.extend_from_slice(&text);
bytes.push(0);
unsafe { out.write(allocate(&bytes).cast()) };
OK
}
extern "system" fn UuidToStringW(uuid: *const Guid, out: *mut *mut u16) -> i32 {
let Some(g) = (unsafe { uuid.as_ref() }) else {
return INVALID_STRING_UUID;
};
if out.is_null() {
return INVALID_STRING_UUID;
}
let text = format(g);
let mut units: Vec<u16> = text.iter().map(|&b| u16::from(b)).collect();
units.push(0);
let bytes: Vec<u8> = units.iter().flat_map(|u| u.to_le_bytes()).collect();
unsafe { out.write(allocate(&bytes).cast()) };
OK
}
extern "system" fn RpcStringFreeA(string: *mut *mut c_char) -> i32 {
free(string.cast());
OK
}
extern "system" fn RpcStringFreeW(string: *mut *mut u16) -> i32 {
free(string.cast());
OK
}
fn from_bytes(b: [u8; 16]) -> Guid {
Guid {
data1: u32::from_le_bytes([b[0], b[1], b[2], b[3]]),
data2: u16::from_le_bytes([b[4], b[5]]),
data3: u16::from_le_bytes([b[6], b[7]]),
data4: [b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]],
}
}
fn format(g: &Guid) -> [u8; 36] {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut text = [b'-'; 36];
let pairs = [
(0, g.data1 as u64, 8),
(9, g.data2 as u64, 4),
(14, g.data3 as u64, 4),
(19, g.data4[0] as u64, 2),
(21, g.data4[1] as u64, 2),
(24, g.data4[2] as u64, 2),
(26, g.data4[3] as u64, 2),
(28, g.data4[4] as u64, 2),
(30, g.data4[5] as u64, 2),
(32, g.data4[6] as u64, 2),
(34, g.data4[7] as u64, 2),
];
for (at, value, digits) in pairs {
for i in 0..digits {
let shift = 4 * (digits - 1 - i);
text[at + i] = HEX[((value >> shift) & 0xf) as usize];
}
}
text
}
fn parse(mut chars: impl Iterator<Item = impl Into<u32>>) -> Option<Guid> {
let mut digits = [0u8; 32];
let mut n = 0;
for c in &mut chars {
let c = c.into();
if n == 32 {
return (c == u32::from(b'}')).then(|| assemble(&digits));
}
if c == u32::from(b'-') || (n == 0 && c == u32::from(b'{')) {
continue;
}
let digit = match c {
0x30..=0x39 => c - 0x30,
0x61..=0x66 => c - 0x61 + 10,
0x41..=0x46 => c - 0x41 + 10,
_ => return None,
};
digits[n] = digit as u8;
n += 1;
}
(n == 32).then(|| assemble(&digits))
}
fn assemble(digits: &[u8; 32]) -> Guid {
let byte = |i: usize| (digits[2 * i] << 4) | digits[2 * i + 1];
Guid {
data1: u32::from_be_bytes([byte(0), byte(1), byte(2), byte(3)]),
data2: u16::from_be_bytes([byte(4), byte(5)]),
data3: u16::from_be_bytes([byte(6), byte(7)]),
data4: [
byte(8),
byte(9),
byte(10),
byte(11),
byte(12),
byte(13),
byte(14),
byte(15),
],
}
}
fn allocate(bytes: &[u8]) -> *mut u8 {
let len = 8 + bytes.len();
let layout = std::alloc::Layout::from_size_align(len, 8).expect("a small allocation");
unsafe {
let base = std::alloc::alloc(layout);
if base.is_null() {
return std::ptr::null_mut();
}
base.cast::<u64>().write_unaligned(bytes.len() as u64);
std::ptr::copy_nonoverlapping(bytes.as_ptr(), base.add(8), bytes.len());
base.add(8)
}
}
fn free(pointer: *mut *mut c_void) {
if pointer.is_null() {
return;
}
unsafe {
let at = pointer.read();
if at.is_null() {
return;
}
let base = at.cast::<u8>().sub(8);
let len = base.cast::<u64>().read_unaligned() as usize;
let layout = std::alloc::Layout::from_size_align(8 + len, 8).expect("a small allocation");
std::alloc::dealloc(base, layout);
pointer.write(std::ptr::null_mut());
}
}
pub(crate) fn module() -> crate::hle::HleModule {
crate::hle::HleModule {
name: "rpcrt4",
dlls: &["rpcrt4.dll"],
exports: vec![
crate::hle_export!(UuidCreate),
crate::hle_export!(UuidCreateSequential),
crate::hle_export!(UuidFromStringA),
crate::hle_export!(UuidFromStringW),
crate::hle_export!(UuidToStringA),
crate::hle_export!(UuidToStringW),
crate::hle_export!(RpcStringFreeA),
crate::hle_export!(RpcStringFreeW),
],
}
}
+110
View File
@@ -0,0 +1,110 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, with_spare,
};
pub const PROVIDER: Guid = Guid::new(
0x3e24_1977,
0x6237,
0x41e9,
[0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1],
);
pub const IID: Guid = Guid::new(
0xd722_b373,
0x8c4d,
0x4692,
[0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d],
);
pub static OBJECT: Object = Object::new("accessibility", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)];
const SILENCE: [u8; 44] =
*b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0";
static SYNTHESIZER: u8 = 0;
static STREAM: u8 = 0;
type This = *const Object;
extern "system" fn enumerate_voices(
_: This,
_context: *mut c_void,
_callback: *const c_void,
) -> HRESULT {
S_OK
}
extern "system" fn create(_: This, out: *mut *const u8) -> HRESULT {
put(out, &raw const SYNTHESIZER)
}
extern "system" fn close(_: This, _: *const u8) -> HRESULT {
S_OK
}
extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT {
S_OK
}
extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT {
S_OK
}
extern "system" fn create_stream(
_: This,
_: *const u8,
words: *const c_char,
out: *mut *const u8,
) -> HRESULT {
tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)");
put(out, &raw const STREAM)
}
extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT {
put(out, SILENCE.len())
}
extern "system" fn stream_data(
_: This,
_: *const u8,
size: usize,
buffer: *mut u8,
used: *mut usize,
) -> HRESULT {
if buffer.is_null() || size < SILENCE.len() {
return super::xasync::E_NOT_SUFFICIENT_BUFFER;
}
unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) };
if !used.is_null() {
unsafe { used.write(SILENCE.len()) };
}
S_OK
}
static VTABLE: Methods<30> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
missing::<3> as *const (),
missing::<4> as *const (),
missing::<5> as *const (),
missing::<6> as *const (),
missing::<7> as *const (),
enumerate_voices as *const (),
create as *const (),
close as *const (),
set_default_voice as *const (),
set_custom_voice as *const (),
create_stream as *const (),
close as *const (),
stream_size as *const (),
stream_data as *const (),
missing::<17> as *const (),
missing::<18> as *const (),
missing::<19> as *const (),
missing::<20> as *const (),
create_stream as *const (),
]);
+192
View File
@@ -0,0 +1,192 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::path::Path;
use super::xasync::{self, AsyncBlock, E_ABORT};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put,
put_string, with_spare,
};
use crate::hle::runtime;
pub const PROVIDER: Guid = Guid::new(
0xf4fa_f4d4,
0x2d04,
0x4fce,
[0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84],
);
pub const IID: Guid = Guid::new(
0xd294_11df,
0x0794,
0x4553,
[0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d],
);
pub const IID_2026: Guid = Guid::new(
0x41a4_e10c,
0x5a7e,
0x41d9,
[0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6],
);
pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
type This = *const Object;
fn folder() -> Option<String> {
let storage = runtime::title().storage;
if storage.as_os_str().is_empty() {
return None;
}
#[cfg(windows)]
return super::files::mount(&storage).map(|letter| format!("{letter}:\\"));
#[cfg(not(windows))]
None
}
extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT {
match folder() {
Some(path) => put(out, path.len() + 1),
None => NOT_SUPPORTED,
}
}
extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
match folder() {
Some(path) if size <= path.len() => E_FAIL,
Some(path) => put_string(&path, size, buffer, used),
None => NOT_SUPPORTED,
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpaceInfo {
pub available_free: u64,
pub total_free: u64,
pub used: u64,
pub total: u64,
}
pub(crate) fn used_bytes(dir: &Path) -> u64 {
let mut pending = vec![dir.to_owned()];
let mut bytes = 0u64;
while let Some(dir) = pending.pop() {
let Ok(metadata) = std::fs::symlink_metadata(&dir) else {
continue;
};
if !metadata.is_dir() || metadata.file_type().is_symlink() {
continue;
}
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(metadata) = std::fs::symlink_metadata(&path) else {
continue;
};
if metadata.file_type().is_symlink() {
continue;
}
if metadata.is_dir() {
pending.push(path);
} else {
bytes = bytes.saturating_add(metadata.len());
}
}
}
bytes
}
pub(crate) fn disk_free(dir: &Path) -> u64 {
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain([0]).collect();
let mut free = 0;
let null = std::ptr::null_mut();
let ok = unsafe {
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
wide.as_ptr(),
&mut free,
null,
null,
)
};
if ok != 0 {
return free;
}
let error = std::io::Error::last_os_error();
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
tracing::warn!(
path = %dir.display(),
%error,
"could not query free storage space; treating it as unlimited"
);
});
}
let _ = dir;
u64::MAX
}
fn space() -> SpaceInfo {
let title = runtime::title();
let used = used_bytes(&title.storage);
let free = title.storage_bytes.saturating_sub(used);
SpaceInfo {
available_free: free.min(disk_free(&title.storage)),
total_free: free,
used,
total: title.storage_bytes,
}
}
extern "system" fn space_info(_: This, out: *mut SpaceInfo) -> HRESULT {
put(out, space())
}
static PROMPT: u8 = 0;
fn prompt_status(bytes: u64, space: SpaceInfo) -> HRESULT {
if bytes <= space.available_free {
S_OK
} else {
E_ABORT
}
}
extern "system" fn prompt_for_space(_: This, bytes: u64, block: *mut AsyncBlock) -> HRESULT {
let hr = prompt_status(bytes, space());
xasync::finished(block, (&raw const PROMPT).cast(), hr)
}
extern "system" fn prompt_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const PROMPT).cast(), 0, none, none.cast())
}
static VTABLE: Methods<17> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
path_size as *const (),
path as *const (),
space_info as *const (),
prompt_for_space as *const (),
prompt_result as *const (),
missing::<8> as *const (),
]);
+111
View File
@@ -0,0 +1,111 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
Auto,
Dark,
Off,
}
impl Mode {
fn parse(text: Option<&str>) -> Mode {
match text.map(str::trim) {
Some("1") => Mode::Dark,
Some("0") => Mode::Off,
_ => Mode::Auto,
}
}
}
fn apps_use_dark(value: Option<u32>) -> bool {
value == Some(0)
}
fn wants_dark(mode: Mode, apps_use_light_theme: Option<u32>) -> Option<bool> {
match mode {
Mode::Off => None,
Mode::Dark => Some(true),
Mode::Auto => Some(apps_use_dark(apps_use_light_theme)),
}
}
fn is_theme_setting(text: &[u16]) -> bool {
text.iter().copied().eq("ImmersiveColorSet".encode_utf16())
}
#[cfg(windows)]
pub(crate) use imp::{apply, apply_for_setting};
#[cfg(windows)]
mod imp {
use super::*;
use windows_sys::Win32::Foundation::{HWND, LPARAM};
use windows_sys::Win32::Graphics::Dwm::{DWMWA_USE_IMMERSIVE_DARK_MODE, DwmSetWindowAttribute};
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_DWORD, RegGetValueW};
use windows_sys::Win32::UI::WindowsAndMessaging as wm;
use windows_sys::core::w;
fn apps_use_light_theme() -> Option<u32> {
let mut value = 0u32;
let mut size = 4u32;
let status = unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
w!("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"),
w!("AppsUseLightTheme"),
RRF_RT_REG_DWORD,
std::ptr::null_mut(),
std::ptr::addr_of_mut!(value).cast(),
&mut size,
)
};
(status == 0).then_some(value)
}
pub(crate) fn apply(hwnd: HWND) {
let setting = std::env::var("EONACAT_XS_DARK_TITLE").ok();
let Some(dark) = wants_dark(Mode::parse(setting.as_deref()), apps_use_light_theme()) else {
return;
};
let value = i32::from(dark);
let ok = unsafe {
let set = |attribute: u32| {
DwmSetWindowAttribute(hwnd, attribute, std::ptr::addr_of!(value).cast(), 4) >= 0
};
set(DWMWA_USE_IMMERSIVE_DARK_MODE as u32) || set(19)
};
if !ok {
tracing::warn!("title bar theme: the window manager refused the attribute");
return;
}
unsafe {
wm::SetWindowPos(
hwnd,
std::ptr::null_mut(),
0,
0,
0,
0,
wm::SWP_FRAMECHANGED | wm::SWP_NOMOVE | wm::SWP_NOSIZE | wm::SWP_NOZORDER | wm::SWP_NOACTIVATE,
);
}
tracing::debug!(dark, "title bar theme applied");
}
pub(crate) fn apply_for_setting(hwnd: HWND, lparam: LPARAM) {
if lparam == 0 {
return;
}
let text = lparam as *const u16;
let seen: Vec<u16> = (0..32).map(|i| unsafe { *text.add(i) }).take_while(|c| *c != 0).collect();
if is_theme_setting(&seen) {
apply(hwnd);
}
}
}
File diff suppressed because it is too large. Load diff
+444
View File
@@ -0,0 +1,444 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
#![allow(clippy::too_many_arguments)]
use std::collections::{HashMap, VecDeque};
use std::ffi::c_void;
use std::sync::{Arc, Mutex, OnceLock};
use eonacat_xsbox_gpu::formats::xma;
use super::xgameruntime::HRESULT;
use crate::hle::{HleExport, HleModule};
use crate::hle_export;
type Ptr = *mut c_void;
macro_rules! once {
($level:ident, $($arg:tt)*) => {{
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::$level!($($arg)*));
}};
}
const WAVE_FORMAT_PCM: u16 = 1;
const WAVE_FORMAT_XMA2: u16 = 0x166;
const XBOX_FLAGS: u32 = 0x0400 | 0x0800 | 0x4000;
const NO_SAMPLES_PLAYED: u32 = 0x0100;
const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32;
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
const PROC_NOT_FOUND: HRESULT = 0x8007_007F_u32 as i32;
#[repr(C, packed)]
#[derive(Clone, Copy, Debug)]
struct WaveFormat {
tag: u16,
channels: u16,
rate: u32,
bytes_per_second: u32,
block_align: u16,
bits: u16,
extra: u16,
}
#[repr(C, packed)]
#[derive(Clone, Copy, Debug)]
struct Xma2Format {
wfx: WaveFormat,
streams: u16,
channel_mask: u32,
samples_encoded: u32,
bytes_per_block: u32,
play_begin: u32,
play_length: u32,
loop_begin: u32,
loop_length: u32,
loop_count: u8,
encoder_version: u8,
blocks: u16,
}
#[repr(C, packed)]
#[derive(Clone, Copy, Debug)]
struct Buffer {
flags: u32,
bytes: u32,
data: *const u8,
play_begin: u32,
play_length: u32,
loop_begin: u32,
loop_length: u32,
loop_count: u32,
context: Ptr,
}
#[repr(C, packed)]
struct VoiceState {
context: Ptr,
queued: u32,
samples_played: u64,
}
const ENGINE_METHODS: usize = 13;
const CREATE_SOURCE_VOICE: usize = 5;
const CREATE_SUBMIX_VOICE: usize = 6;
const CREATE_MASTERING_VOICE: usize = 7;
const SOURCE_METHODS: usize = 29;
const DESTROY_VOICE: usize = 18;
const SUBMIT_SOURCE_BUFFER: usize = 21;
const FLUSH_SOURCE_BUFFERS: usize = 22;
const GET_STATE: usize = 25;
fn table(object: Ptr) -> *const usize {
unsafe { *object.cast::<*const usize>() }
}
fn patch(object: Ptr, methods: usize, ours: &[(usize, usize)]) {
static COPIES: Mutex<Option<HashMap<(usize, usize), usize>>> = Mutex::new(None);
let host = table(object);
let mut copies = COPIES.lock().unwrap_or_else(|e| e.into_inner());
let copy = *copies.get_or_insert_with(HashMap::new).entry((host as usize, methods)).or_insert_with(|| {
let mut copy: Vec<usize> = (0..methods).map(|i| unsafe { *host.add(i) }).collect();
for &(slot, f) in ours {
copy[slot] = f;
}
copy.push(host as usize);
Box::leak(copy.into_boxed_slice()).as_ptr() as usize
});
unsafe { object.cast::<usize>().write(copy) };
}
unsafe fn original<F: Copy>(object: Ptr, methods: usize, slot: usize) -> F {
unsafe {
let host = *table(object).add(methods) as *const usize;
std::mem::transmute_copy(&*host.add(slot))
}
}
extern "system" fn create_source_voice(
this: Ptr,
voice: *mut Ptr,
format: *const WaveFormat,
flags: u32,
max_ratio: f32,
callback: Ptr,
sends: Ptr,
effects: Ptr,
) -> HRESULT {
let create: extern "system" fn(Ptr, *mut Ptr, *const WaveFormat, u32, f32, Ptr, Ptr, Ptr) -> HRESULT =
unsafe { original(this, ENGINE_METHODS, CREATE_SOURCE_VOICE) };
let flags = flags & !XBOX_FLAGS;
let tag = (!format.is_null()).then(|| unsafe { format.read_unaligned() }.tag);
if tag != Some(WAVE_FORMAT_XMA2) {
return create(this, voice, format, flags, max_ratio, callback, sends, effects);
}
let xma2 = unsafe { format.cast::<Xma2Format>().read_unaligned() };
let Some(streams) = streams(xma2.wfx.channels, xma2.streams) else {
let (channels, streams) = (xma2.wfx.channels, xma2.streams);
tracing::warn!(channels, streams, "XAudio2: an XMA2 format with channels and streams that do not fit");
return E_INVALIDARG;
};
let (channels, rate) = (xma2.wfx.channels, xma2.wfx.rate);
let pcm = WaveFormat {
tag: WAVE_FORMAT_PCM,
channels,
rate,
bytes_per_second: rate * u32::from(channels) * 2,
block_align: channels * 2,
bits: 16,
extra: 0,
};
let hr = create(this, voice, &pcm, flags, max_ratio, callback, sends, effects);
if hr < 0 || voice.is_null() {
return hr;
}
let made = unsafe { *voice };
if made.is_null() {
return hr;
}
patch(
made,
SOURCE_METHODS,
&[
(DESTROY_VOICE, destroy_voice as *const () as usize),
(SUBMIT_SOURCE_BUFFER, submit_source_buffer as *const () as usize),
(FLUSH_SOURCE_BUFFERS, flush_source_buffers as *const () as usize),
],
);
let decoders = streams.iter().map(|&c| (xma::Decoder::new(c, rate), c)).collect();
voices().insert(made as usize, Arc::new(Mutex::new(Xma { decoders, channels: channels.into(), kept: VecDeque::new() })));
once!(info, channels, rate, "XAudio2: an XMA2 source voice, decoded here into a PCM voice");
hr
}
extern "system" fn create_submix_voice(
this: Ptr,
voice: *mut Ptr,
channels: u32,
rate: u32,
flags: u32,
stage: u32,
sends: Ptr,
effects: Ptr,
) -> HRESULT {
let create: extern "system" fn(Ptr, *mut Ptr, u32, u32, u32, u32, Ptr, Ptr) -> HRESULT =
unsafe { original(this, ENGINE_METHODS, CREATE_SUBMIX_VOICE) };
create(this, voice, channels, rate, flags & !XBOX_FLAGS, stage, sends, effects)
}
extern "system" fn create_mastering_voice(
this: Ptr,
voice: *mut Ptr,
channels: u32,
rate: u32,
flags: u32,
device: *const u16,
effects: Ptr,
category: u32,
) -> HRESULT {
let create: extern "system" fn(Ptr, *mut Ptr, u32, u32, u32, *const u16, Ptr, u32) -> HRESULT =
unsafe { original(this, ENGINE_METHODS, CREATE_MASTERING_VOICE) };
create(this, voice, channels, rate, flags & !XBOX_FLAGS, device, effects, category)
}
fn streams(channels: u16, streams: u16) -> Option<Vec<usize>> {
let (channels, streams) = (usize::from(channels), usize::from(streams));
if channels == 0 || streams == 0 || channels > 2 * streams || channels < streams {
return None;
}
if channels == streams {
return Some(vec![1; streams]);
}
let last = channels.checked_sub(2 * (streams - 1)).filter(|c| (1..=2).contains(c))?;
Some((0..streams).map(|s| if s + 1 == streams { last } else { 2 }).collect())
}
struct Xma {
decoders: Vec<(xma::Decoder, usize)>,
channels: usize,
kept: VecDeque<Box<[i16]>>,
}
type Voices = HashMap<usize, Arc<Mutex<Xma>>>;
fn voices() -> std::sync::MutexGuard<'static, Voices> {
static VOICES: std::sync::LazyLock<Mutex<Voices>> = std::sync::LazyLock::new(Default::default);
VOICES.lock().unwrap_or_else(|e| e.into_inner())
}
fn voice(this: Ptr) -> Option<Arc<Mutex<Xma>>> {
voices().get(&(this as usize)).cloned()
}
fn lock(v: &Mutex<Xma>) -> std::sync::MutexGuard<'_, Xma> {
v.lock().unwrap_or_else(|e| e.into_inner())
}
fn decode(voice: &mut Xma, data: &[u8]) -> Vec<i16> {
let mut outs = Vec::with_capacity(voice.decoders.len());
let mut bad = 0;
for (s, (decoder, _)) in voice.decoders.iter_mut().enumerate() {
let mut out = Vec::new();
if let Some(packet) = xma::packet(data, s) {
let mut at = s * xma::PACKET_BYTES * 8 + 32 + packet.first_frame_bit as usize;
while let Some(frame) = xma::read_frame(data, at) {
bad += usize::from(decoder.decode(&frame.data, frame.bits, &mut out).is_err());
match frame.next {
Some(next) if next > at => at = next,
_ => break,
}
}
}
outs.push(out);
}
if bad > 0 {
once!(warn, bad, "XAudio2: XMA2 frames that did not decode (silence in their place)");
}
let frames = outs.iter().zip(&voice.decoders).map(|(o, (_, c))| o.len() / c).min().unwrap_or(0);
let mut pcm = Vec::with_capacity(frames * voice.channels);
for f in 0..frames {
for (out, (_, c)) in outs.iter().zip(&voice.decoders) {
pcm.extend_from_slice(&out[f * c..f * c + c]);
}
}
pcm
}
fn fit(buffer: &Buffer, frames: u32) -> Buffer {
let mut b = *buffer;
if b.play_begin >= frames || b.play_begin.saturating_add(b.play_length) > frames {
(b.play_begin, b.play_length) = (0, 0);
}
let play_end = if b.play_length == 0 { frames } else { b.play_begin + b.play_length };
let loop_end = if b.loop_length == 0 { play_end } else { b.loop_begin.saturating_add(b.loop_length) };
if b.loop_count != 0 && (b.loop_begin >= play_end || loop_end > play_end) {
(b.loop_begin, b.loop_length, b.loop_count) = (0, 0, 0);
}
if b.loop_count == 0 {
(b.loop_begin, b.loop_length) = (0, 0);
}
b
}
extern "system" fn submit_source_buffer(this: Ptr, buffer: *const Buffer, wma: Ptr) -> HRESULT {
let submit: extern "system" fn(Ptr, *const Buffer, Ptr) -> HRESULT =
unsafe { original(this, SOURCE_METHODS, SUBMIT_SOURCE_BUFFER) };
let Some(voice) = voice(this) else {
return submit(this, buffer, wma);
};
if buffer.is_null() {
return E_POINTER;
}
let asked = unsafe { buffer.read_unaligned() };
let data: &[u8] = if asked.data.is_null() || asked.bytes == 0 {
&[]
} else {
unsafe { std::slice::from_raw_parts(asked.data, asked.bytes as usize) }
};
let (pcm, channels) = {
let mut v = lock(&voice);
let mut pcm = decode(&mut v, data);
if pcm.is_empty() {
pcm = vec![0; xma::SUBFRAME_SAMPLES * v.channels];
}
(pcm.into_boxed_slice(), v.channels)
};
let frames = (pcm.len() / channels) as u32;
let mut shown = fit(&asked, frames);
shown.bytes = (pcm.len() * 2) as u32;
shown.data = pcm.as_ptr().cast();
let hr = submit(this, &shown, std::ptr::null_mut());
if hr < 0 {
return hr;
}
lock(&voice).kept.push_back(pcm);
let get_state: extern "system" fn(Ptr, *mut VoiceState, u32) =
unsafe { original(this, SOURCE_METHODS, GET_STATE) };
let mut state = VoiceState { context: std::ptr::null_mut(), queued: u32::MAX, samples_played: 0 };
get_state(this, &mut state, NO_SAMPLES_PLAYED);
let mut v = lock(&voice);
while v.kept.len() > state.queued as usize + 1 {
v.kept.pop_front();
}
hr
}
extern "system" fn flush_source_buffers(this: Ptr) -> HRESULT {
let flush: extern "system" fn(Ptr) -> HRESULT = unsafe { original(this, SOURCE_METHODS, FLUSH_SOURCE_BUFFERS) };
let hr = flush(this);
if let Some(voice) = voice(this) {
for (decoder, _) in &mut lock(&voice).decoders {
decoder.reset();
}
}
hr
}
extern "system" fn destroy_voice(this: Ptr) {
let destroy: extern "system" fn(Ptr) = unsafe { original(this, SOURCE_METHODS, DESTROY_VOICE) };
destroy(this);
voices().remove(&(this as usize));
}
fn engine(out: *mut Ptr, hr: HRESULT) -> HRESULT {
if hr >= 0 && !out.is_null() {
let made = unsafe { *out };
if !made.is_null() {
patch(
made,
ENGINE_METHODS,
&[
(CREATE_SOURCE_VOICE, create_source_voice as *const () as usize),
(CREATE_SUBMIX_VOICE, create_submix_voice as *const () as usize),
(CREATE_MASTERING_VOICE, create_mastering_voice as *const () as usize),
],
);
}
}
hr
}
fn keep_com() {
static KEPT: OnceLock<()> = OnceLock::new();
KEPT.get_or_init(|| {
let hr = crate::hle::host::function("ole32.dll", "CoIncrementMTAUsage").map_or(PROC_NOT_FOUND, |f| {
let keep: extern "system" fn(*mut usize) -> HRESULT = unsafe { std::mem::transmute(f) };
keep(&mut 0)
});
if hr < 0 {
tracing::warn!(hr = format_args!("{hr:#x}"), "XAudio2: the multithreaded apartment was not kept; a mastering voice may fail");
}
});
}
fn host_create(out: *mut Ptr, flags: u32, processor: u32) -> HRESULT {
keep_com();
static CREATE: OnceLock<Option<usize>> = OnceLock::new();
let Some(create) = *CREATE.get_or_init(|| crate::hle::host::function("xaudio2_9.dll", "XAudio2Create")) else {
return PROC_NOT_FOUND;
};
let create: extern "system" fn(*mut Ptr, u32, u32) -> HRESULT = unsafe { std::mem::transmute(create) };
engine(out, create(out, flags & !XBOX_FLAGS, processor))
}
pub extern "system" fn XAudio2Create(out: *mut Ptr, flags: u32, processor: u32) -> HRESULT {
host_create(out, flags, processor)
}
pub extern "system" fn XAudio2CreateWithVersionInfo(out: *mut Ptr, flags: u32, processor: u32, _ntddi: u32) -> HRESULT {
host_create(out, flags, processor)
}
pub extern "system" fn XAudio2CreateWithSharedContexts(
out: *mut Ptr,
flags: u32,
processor: u32,
_contexts: Ptr,
) -> HRESULT {
host_create(out, flags, processor)
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "xaudio2",
dlls: &["xaudio2_9.dll"],
exports: vec![
hle_export!(XAudio2Create),
HleExport { name: "#1", address: XAudio2Create as *const () as usize },
hle_export!(XAudio2CreateWithVersionInfo),
hle_export!(XAudio2CreateWithSharedContexts),
],
}
}
+162
View File
@@ -0,0 +1,162 @@
use std::ffi::c_void;
use eonacat_xsbox_gpu::hwrt::{
XboxBatchedBuildDesc2, XboxBuildDesc, XboxBuildInputs, XboxPostbuildDesc, XboxPrebuildInfo,
};
use eonacat_xsbox_gpu::object::{HRESULT, Object, S_OK};
type This = *const Object;
use crate::hle::{HleExport, HleModule};
extern "system" fn ctor(
this: *mut [usize; 3],
_device: This,
rehydrate_only: bool,
) -> *mut [usize; 3] {
if !this.is_null() {
unsafe { *this = [0, 0, 0] };
}
tracing::info!(rehydrate_only, "HLE XboxBvhBuilder constructed (hardware DXR 1.1)");
this
}
extern "system" fn dtor(this: *mut [usize; 3]) {
if !this.is_null() {
unsafe { *this = [0, 0, 0] };
}
}
extern "system" fn set_64bit_morton(_this: *mut c_void, _enable: bool) {}
extern "system" fn get_prebuild_info(
_this: *mut c_void,
inputs: *const XboxBuildInputs,
stream_desc: *const u8,
out: *mut XboxPrebuildInfo,
) {
eonacat_xsbox_gpu::hwrt::prebuild_info(inputs, stream_desc, out);
}
extern "system" fn build_single(
_this: *mut c_void,
list: This,
desc: *const XboxBuildDesc,
num_postbuild: u32,
postbuild: *const XboxPostbuildDesc,
) {
eonacat_xsbox_gpu::hwrt::build_single(list, desc, num_postbuild, postbuild);
}
extern "system" fn build_batched2(
_this: *mut c_void,
list: This,
num_descs: u32,
descs: *const XboxBatchedBuildDesc2,
) {
eonacat_xsbox_gpu::hwrt::build_batched2(list, num_descs, descs);
}
extern "system" fn copy_as(
_this: *mut c_void,
list: This,
dest_va: u64,
src_va: u64,
mode: u32,
) {
eonacat_xsbox_gpu::hwrt::copy_as(list, dest_va, src_va, mode);
}
extern "system" fn rehydrate_batched2(
_this: *mut c_void,
list: This,
num_descs: u32,
descs: *const XboxBuildDesc,
src_vas: *const u64,
) -> HRESULT {
eonacat_xsbox_gpu::hwrt::rehydrate_batched2(list, num_descs, descs, src_vas)
}
extern "system" fn rehydrate_batched(
_this: *mut c_void,
list: This,
num_descs: u32,
descs: *const XboxBuildDesc,
) -> HRESULT {
eonacat_xsbox_gpu::hwrt::rehydrate_batched2(list, num_descs, descs, std::ptr::null())
}
extern "system" fn rehydrate_cpu(
_this: *mut c_void,
_device: This,
_desc: *const XboxBuildDesc,
) -> HRESULT {
S_OK
}
extern "system" fn validate_rehydrate(_this: *mut c_void, _desc: *const XboxBuildDesc) -> HRESULT {
S_OK
}
extern "system" fn cpu_validate(_this: *mut c_void, _list: This, _desc: *const XboxBuildDesc) {}
pub(crate) fn module() -> HleModule {
HleModule {
name: "xboxbvh",
dlls: &["xboxbvhbuilder.dll"],
exports: vec![
HleExport {
name: "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z",
address: ctor as *const () as usize,
},
HleExport {
name: "??1XboxBvhBuilder@@QEAA@XZ",
address: dtor as *const () as usize,
},
HleExport {
name: "?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z",
address: set_64bit_morton as *const () as usize,
},
HleExport {
name: "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z",
address: get_prebuild_info as *const () as usize,
},
HleExport {
name: "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z",
address: build_single as *const () as usize,
},
HleExport {
name: "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z",
address: build_batched2 as *const () as usize,
},
HleExport {
name: "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z",
address: copy_as as *const () as usize,
},
HleExport {
name: "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z",
address: rehydrate_batched2 as *const () as usize,
},
HleExport {
name: "?RehydrateRaytracingAccelerationStructureBatchedX@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@@Z",
address: rehydrate_batched as *const () as usize,
},
HleExport {
name: "?RehydrateRaytracingAccelerationStructureX@XboxBvhBuilder@@QEAAJPEAUID3D12Device11@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@@Z",
address: rehydrate_cpu as *const () as usize,
},
HleExport {
name: "?ValidateRehydrateAccelerationStructureBuildDesc@XboxBvhBuilder@@QEAAJPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@@Z",
address: validate_rehydrate as *const () as usize,
},
HleExport {
name: "?CpuValidateResultX@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@@Z",
address: cpu_validate as *const () as usize,
},
],
}
}
+787
View File
@@ -0,0 +1,787 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::collections::VecDeque;
use std::ffi::{CStr, c_char, c_int, c_long, c_uint, c_void};
use std::sync::OnceLock;
use crate::hle::{HleModule};
use crate::hle_export;
type Code = c_int;
const CURLE_OK: Code = 0;
const CURLE_COULDNT_RESOLVE_HOST: Code = 6;
const CURLE_BAD_FUNCTION_ARGUMENT: Code = 43;
const CURL_ERROR_SIZE: usize = 256;
const CURLOPT_URL: c_int = 10_002;
const CURLOPT_ERRORBUFFER: c_int = 10_010;
const CURLOPT_PRIVATE: c_int = 10_103;
const CURLINFO_TYPEMASK: c_int = 0xf0_0000;
const CURLINFO_STRING: c_int = 0x10_0000;
const CURLINFO_LONG: c_int = 0x20_0000;
const CURLINFO_DOUBLE: c_int = 0x30_0000;
const CURLINFO_PTR: c_int = 0x40_0000;
const CURLINFO_SOCKET: c_int = 0x50_0000;
const CURLINFO_OFF_T: c_int = 0x60_0000;
const CURLINFO_EFFECTIVE_URL: c_int = CURLINFO_STRING + 1;
const CURLINFO_PRIVATE: c_int = CURLINFO_STRING + 21;
const OFFLINE: &CStr = c"Could not resolve host: the console is offline";
fn text(s: *const c_char) -> Option<&'static CStr> {
(!s.is_null()).then(|| unsafe { CStr::from_ptr(s) })
}
fn give(bytes: &[u8]) -> *mut c_char {
let mut b = Vec::with_capacity(8 + bytes.len() + 1);
b.extend_from_slice(&(bytes.len() + 1).to_le_bytes());
b.extend_from_slice(bytes);
b.push(0);
let b = Box::leak(b.into_boxed_slice());
unsafe { b.as_mut_ptr().add(8).cast() }
}
pub extern "C" fn curl_free(p: *mut c_void) {
if p.is_null() {
return;
}
unsafe {
let base = p.cast::<u8>().sub(8);
let len = usize::from_le_bytes(base.cast::<[u8; 8]>().read());
drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(base, 8 + len)));
}
}
pub extern "C" fn curl_global_init(_flags: c_long) -> Code {
tracing::info!("XCurl: initialized (offline: every transfer fails to resolve its host)");
CURLE_OK
}
pub extern "C" fn curl_global_init_mem(_flags: c_long, _m: Ptr, _f: Ptr, _r: Ptr, _s: Ptr, _c: Ptr) -> Code {
curl_global_init(0)
}
pub extern "C" fn xcurl_global_init_mem(_flags: c_long, _m: Ptr, _f: Ptr, _r: Ptr, _s: Ptr, _c: Ptr) -> Code {
curl_global_init(0)
}
pub extern "C" fn curl_global_cleanup() {}
pub extern "C" fn xcurl_global_suspend() {}
pub extern "C" fn xcurl_global_resume() {}
pub extern "C" fn xcurl_global_set_request_limit(_limit: c_uint) {}
pub extern "C" fn curl_global_sslset(_id: c_int, _name: *const c_char, avail: *mut *const c_void) -> c_int {
if !avail.is_null() {
unsafe { avail.write(EMPTY.as_ptr().cast()) };
}
0
}
static EMPTY: [usize; 1] = [0];
type Ptr = *const c_void;
#[derive(Clone, Default)]
pub struct Easy {
private: usize,
error_buffer: usize,
url: Option<Box<CStr>>,
}
fn easy<'a>(h: *mut Easy) -> Option<&'a mut Easy> {
unsafe { h.as_mut() }
}
pub extern "C" fn curl_easy_init() -> *mut Easy {
Box::into_raw(Box::default())
}
pub extern "C" fn curl_easy_cleanup(h: *mut Easy) {
if !h.is_null() {
drop(unsafe { Box::from_raw(h) });
}
}
pub extern "C" fn curl_easy_duphandle(h: *mut Easy) -> *mut Easy {
easy(h).map_or(std::ptr::null_mut(), |e| Box::into_raw(Box::new(e.clone())))
}
pub extern "C" fn curl_easy_reset(h: *mut Easy) {
if let Some(e) = easy(h) {
*e = Easy::default();
}
}
pub extern "C" fn curl_easy_setopt(h: *mut Easy, option: c_int, value: usize) -> Code {
let Some(e) = easy(h) else {
return CURLE_BAD_FUNCTION_ARGUMENT;
};
match option {
CURLOPT_PRIVATE => e.private = value,
CURLOPT_ERRORBUFFER => e.error_buffer = value,
CURLOPT_URL => e.url = text(value as *const c_char).map(Box::from),
_ => {}
}
CURLE_OK
}
pub extern "C" fn curl_easy_perform(h: *mut Easy) -> Code {
let Some(e) = easy(h) else {
return CURLE_BAD_FUNCTION_ARGUMENT;
};
fail(e)
}
fn fail(e: &Easy) -> Code {
tracing::debug!(url = ?e.url, "XCurl: transfer refused (offline)");
if e.error_buffer != 0 {
let message = OFFLINE.to_bytes_with_nul();
unsafe {
std::ptr::copy_nonoverlapping(message.as_ptr(), e.error_buffer as *mut u8, message.len().min(CURL_ERROR_SIZE));
}
}
CURLE_COULDNT_RESOLVE_HOST
}
pub extern "C" fn curl_easy_getinfo(h: *mut Easy, info: c_int, out: *mut c_void) -> Code {
let Some(e) = easy(h) else {
return CURLE_BAD_FUNCTION_ARGUMENT;
};
if out.is_null() {
return CURLE_BAD_FUNCTION_ARGUMENT;
}
unsafe {
match (info, info & CURLINFO_TYPEMASK) {
(CURLINFO_PRIVATE, _) => out.cast::<usize>().write(e.private),
(CURLINFO_EFFECTIVE_URL, _) => {
out.cast::<*const c_char>().write(e.url.as_deref().map_or(c"".as_ptr(), CStr::as_ptr));
}
(_, CURLINFO_STRING) => out.cast::<*const c_char>().write(c"".as_ptr()),
(_, CURLINFO_LONG) => out.cast::<c_long>().write(0),
(_, CURLINFO_DOUBLE) => out.cast::<f64>().write(0.0),
(_, CURLINFO_PTR) => out.cast::<usize>().write(0),
(_, CURLINFO_SOCKET) => out.cast::<usize>().write(usize::MAX),
(_, CURLINFO_OFF_T) => out.cast::<i64>().write(0),
_ => return CURLE_BAD_FUNCTION_ARGUMENT,
}
}
CURLE_OK
}
pub extern "C" fn curl_easy_strerror(code: Code) -> *const c_char {
match code {
CURLE_OK => c"No error",
CURLE_COULDNT_RESOLVE_HOST => c"Couldn't resolve host name",
CURLE_BAD_FUNCTION_ARGUMENT => c"A libcurl function was given a bad argument",
_ => c"Error (XCurl offline)",
}
.as_ptr()
}
fn escape(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(bytes.len() * 3);
for &b in bytes {
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
out.push(b);
} else {
out.extend_from_slice(format!("%{b:02X}").as_bytes());
}
}
out
}
fn unescape(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let hex = bytes.get(i + 1..i + 3).filter(|h| h.iter().all(u8::is_ascii_hexdigit));
match (bytes[i], hex) {
(b'%', Some(h)) => {
out.push(u8::from_str_radix(std::str::from_utf8(h).unwrap_or("0"), 16).unwrap_or(0));
i += 3;
}
(b, _) => {
out.push(b);
i += 1;
}
}
}
out
}
fn input<'a>(s: *const c_char, len: c_int) -> Option<&'a [u8]> {
if s.is_null() {
return None;
}
Some(match usize::try_from(len).unwrap_or(0) {
0 => text(s)?.to_bytes(),
n => unsafe { std::slice::from_raw_parts(s.cast(), n) },
})
}
pub extern "C" fn curl_easy_escape(_h: *mut Easy, s: *const c_char, len: c_int) -> *mut c_char {
input(s, len).map_or(std::ptr::null_mut(), |b| give(&escape(b)))
}
pub extern "C" fn curl_escape(s: *const c_char, len: c_int) -> *mut c_char {
curl_easy_escape(std::ptr::null_mut(), s, len)
}
pub extern "C" fn curl_easy_unescape(_h: *mut Easy, s: *const c_char, len: c_int, out_len: *mut c_int) -> *mut c_char {
let Some(b) = input(s, len) else {
return std::ptr::null_mut();
};
let plain = unescape(b);
if !out_len.is_null() {
unsafe { out_len.write(plain.len() as c_int) };
}
give(&plain)
}
pub extern "C" fn curl_unescape(s: *const c_char, len: c_int) -> *mut c_char {
curl_easy_unescape(std::ptr::null_mut(), s, len, std::ptr::null_mut())
}
pub extern "C" fn curl_getdate(_s: *const c_char, _unused: *const i64) -> i64 {
-1
}
#[repr(C)]
pub struct Slist {
data: *mut c_char,
next: *mut Slist,
}
pub extern "C" fn curl_slist_append(list: *mut Slist, s: *const c_char) -> *mut Slist {
let Some(s) = text(s) else {
return std::ptr::null_mut();
};
let node = Box::into_raw(Box::new(Slist { data: give(s.to_bytes()), next: std::ptr::null_mut() }));
if list.is_null() {
return node;
}
let mut at = list;
unsafe {
while !(*at).next.is_null() {
at = (*at).next;
}
(*at).next = node;
}
list
}
pub extern "C" fn curl_slist_free_all(list: *mut Slist) {
let mut at = list;
while !at.is_null() {
let node = unsafe { Box::from_raw(at) };
curl_free(node.data.cast());
at = node.next;
}
}
pub struct Mime {
#[allow(clippy::vec_box)]
parts: Vec<Box<u8>>,
}
pub extern "C" fn curl_mime_init(_h: *mut Easy) -> *mut Mime {
Box::into_raw(Box::new(Mime { parts: Vec::new() }))
}
pub extern "C" fn curl_mime_free(m: *mut Mime) {
if !m.is_null() {
drop(unsafe { Box::from_raw(m) });
}
}
pub extern "C" fn curl_mime_addpart(m: *mut Mime) -> *mut c_void {
let Some(m) = (unsafe { m.as_mut() }) else {
return std::ptr::null_mut();
};
m.parts.push(Box::new(0));
let part: &mut u8 = m.parts.last_mut().expect("just pushed");
(part as *mut u8).cast()
}
pub extern "C" fn curl_mime_name(_p: Ptr, _s: *const c_char) -> Code {
CURLE_OK
}
pub extern "C" fn curl_mime_filename(_p: Ptr, _s: *const c_char) -> Code {
CURLE_OK
}
pub extern "C" fn curl_mime_type(_p: Ptr, _s: *const c_char) -> Code {
CURLE_OK
}
pub extern "C" fn curl_mime_encoder(_p: Ptr, _s: *const c_char) -> Code {
CURLE_OK
}
pub extern "C" fn curl_mime_filedata(_p: Ptr, _s: *const c_char) -> Code {
CURLE_OK
}
pub extern "C" fn curl_mime_data(_p: Ptr, _data: *const c_char, _size: usize) -> Code {
CURLE_OK
}
pub extern "C" fn curl_mime_data_cb(_p: Ptr, _size: i64, _read: Ptr, _seek: Ptr, _free: Ptr, _arg: Ptr) -> Code {
CURLE_OK
}
pub extern "C" fn curl_mime_subparts(_p: Ptr, _m: *mut Mime) -> Code {
CURLE_OK
}
pub extern "C" fn curl_mime_headers(_p: Ptr, _headers: *mut Slist, _take: c_int) -> Code {
CURLE_OK
}
pub extern "C" fn curl_formadd(_post: *mut Ptr, _last: *mut Ptr, _option: c_int) -> c_int {
7
}
pub extern "C" fn curl_formget(_form: Ptr, _arg: Ptr, _append: Ptr) -> c_int {
0
}
pub extern "C" fn curl_formfree(_form: Ptr) {}
type MultiCode = c_int;
const CURLM_OK: MultiCode = 0;
const CURLM_BAD_HANDLE: MultiCode = 1;
const CURLM_BAD_EASY_HANDLE: MultiCode = 2;
const CURLM_ADDED_ALREADY: MultiCode = 7;
const CURLMSG_DONE: c_int = 1;
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Message {
msg: c_int,
easy: *mut Easy,
result: usize,
}
pub struct Multi {
handles: Vec<(*mut Easy, bool)>,
messages: VecDeque<Message>,
current: Message,
}
fn multi<'a>(m: *mut Multi) -> Option<&'a mut Multi> {
unsafe { m.as_mut() }
}
pub extern "C" fn curl_multi_init() -> *mut Multi {
Box::into_raw(Box::new(Multi {
handles: Vec::new(),
messages: VecDeque::new(),
current: Message { msg: 0, easy: std::ptr::null_mut(), result: 0 },
}))
}
pub extern "C" fn curl_multi_cleanup(m: *mut Multi) -> MultiCode {
if m.is_null() {
return CURLM_BAD_HANDLE;
}
drop(unsafe { Box::from_raw(m) });
CURLM_OK
}
pub extern "C" fn curl_multi_add_handle(m: *mut Multi, e: *mut Easy) -> MultiCode {
let Some(m) = multi(m) else {
return CURLM_BAD_HANDLE;
};
if e.is_null() {
return CURLM_BAD_EASY_HANDLE;
}
if m.handles.iter().any(|(h, _)| *h == e) {
return CURLM_ADDED_ALREADY;
}
m.handles.push((e, false));
CURLM_OK
}
pub extern "C" fn curl_multi_remove_handle(m: *mut Multi, e: *mut Easy) -> MultiCode {
let Some(m) = multi(m) else {
return CURLM_BAD_HANDLE;
};
m.handles.retain(|(h, _)| *h != e);
m.messages.retain(|msg| msg.easy != e);
CURLM_OK
}
pub extern "C" fn curl_multi_perform(m: *mut Multi, running: *mut c_int) -> MultiCode {
let Some(m) = multi(m) else {
return CURLM_BAD_HANDLE;
};
for (e, done) in &mut m.handles {
if !*done {
*done = true;
let result = easy(*e).map_or(CURLE_COULDNT_RESOLVE_HOST, |e| fail(e));
m.messages.push_back(Message { msg: CURLMSG_DONE, easy: *e, result: result as usize });
}
}
if !running.is_null() {
unsafe { running.write(0) };
}
CURLM_OK
}
pub extern "C" fn curl_multi_info_read(m: *mut Multi, left: *mut c_int) -> *mut Message {
let Some(m) = multi(m) else {
return std::ptr::null_mut();
};
let next = m.messages.pop_front();
if !left.is_null() {
unsafe { left.write(m.messages.len() as c_int) };
}
match next {
Some(msg) => {
m.current = msg;
&raw mut m.current
}
None => std::ptr::null_mut(),
}
}
pub extern "C" fn curl_multi_wait(m: *mut Multi, _fds: Ptr, _n: c_uint, _timeout_ms: c_int, ready: *mut c_int) -> MultiCode {
if m.is_null() {
return CURLM_BAD_HANDLE;
}
if !ready.is_null() {
unsafe { ready.write(0) };
}
CURLM_OK
}
pub extern "C" fn curl_multi_poll(m: *mut Multi, fds: Ptr, n: c_uint, timeout_ms: c_int, ready: *mut c_int) -> MultiCode {
curl_multi_wait(m, fds, n, timeout_ms, ready)
}
pub extern "C" fn curl_multi_wakeup(m: *mut Multi) -> MultiCode {
if m.is_null() { CURLM_BAD_HANDLE } else { CURLM_OK }
}
pub extern "C" fn curl_multi_setopt(m: *mut Multi, _option: c_int, _value: usize) -> MultiCode {
if m.is_null() { CURLM_BAD_HANDLE } else { CURLM_OK }
}
pub extern "C" fn curl_multi_strerror(code: MultiCode) -> *const c_char {
match code {
CURLM_OK => c"No error",
CURLM_BAD_HANDLE => c"Invalid multi handle",
CURLM_BAD_EASY_HANDLE => c"Invalid easy handle",
CURLM_ADDED_ALREADY => c"The easy handle is already added to a multi handle",
_ => c"Error (XCurl offline)",
}
.as_ptr()
}
pub extern "C" fn curl_share_init() -> *mut u8 {
Box::into_raw(Box::new(0u8))
}
pub extern "C" fn curl_share_setopt(s: *mut u8, _option: c_int, _value: usize) -> c_int {
if s.is_null() { 3 } else { 0 }
}
pub extern "C" fn curl_share_cleanup(s: *mut u8) -> c_int {
if s.is_null() {
return 3;
}
drop(unsafe { Box::from_raw(s) });
0
}
pub extern "C" fn curl_share_strerror(code: c_int) -> *const c_char {
if code == 0 { c"No error" } else { c"Invalid share handle" }.as_ptr()
}
type UrlCode = c_int;
const CURLUE_OK: UrlCode = 0;
const CURLUE_BAD_HANDLE: UrlCode = 1;
const CURLUE_BAD_PARTPOINTER: UrlCode = 2;
const CURLUE_MALFORMED_INPUT: UrlCode = 3;
const CURLUE_UNKNOWN_PART: UrlCode = 9;
fn no_part(index: usize) -> UrlCode {
match index {
1..=6 => 9 + index as UrlCode,
8 => 16,
9 => 17,
_ => 13,
}
}
const URL: c_int = 0;
const PARTS: usize = 11;
#[derive(Clone, Default)]
pub struct Url {
parts: [Option<String>; PARTS],
}
impl Url {
fn parse(&mut self, url: &str) -> bool {
let Some((scheme, rest)) = url.split_once("://") else {
return false;
};
let (rest, fragment) = rest.split_once('#').map_or((rest, None), |(a, b)| (a, Some(b)));
let (rest, query) = rest.split_once('?').map_or((rest, None), |(a, b)| (a, Some(b)));
let (authority, path) = rest.find('/').map_or((rest, "/"), |i| (&rest[..i], &rest[i..]));
let (user_info, host_port) = authority.rsplit_once('@').map_or((None, authority), |(a, b)| (Some(a), b));
let (user, password) = match user_info {
Some(u) => u.split_once(':').map_or((Some(u), None), |(a, b)| (Some(a), Some(b))),
None => (None, None),
};
let (host, port) = match host_port.rsplit_once(':') {
Some((h, p)) if !p.contains(']') && p.bytes().all(|b| b.is_ascii_digit()) => (h, Some(p)),
_ => (host_port, None),
};
if host.is_empty() {
return false;
}
let owned = |s: Option<&str>| s.map(str::to_owned);
self.parts = Default::default();
self.parts[1] = Some(scheme.to_owned());
self.parts[2] = owned(user);
self.parts[3] = owned(password);
self.parts[5] = Some(host.to_owned());
self.parts[6] = owned(port);
self.parts[7] = Some(path.to_owned());
self.parts[8] = owned(query);
self.parts[9] = owned(fragment);
true
}
fn whole(&self) -> Option<String> {
let p = &self.parts;
let mut out = format!("{}://", p[1].as_deref()?);
if let Some(user) = &p[2] {
out.push_str(user);
if let Some(password) = &p[3] {
out.push(':');
out.push_str(password);
}
out.push('@');
}
out.push_str(p[5].as_deref()?);
if let Some(port) = &p[6] {
out.push(':');
out.push_str(port);
}
out.push_str(p[7].as_deref().unwrap_or("/"));
if let Some(query) = &p[8] {
out.push('?');
out.push_str(query);
}
if let Some(fragment) = &p[9] {
out.push('#');
out.push_str(fragment);
}
Some(out)
}
}
fn url<'a>(u: *mut Url) -> Option<&'a mut Url> {
unsafe { u.as_mut() }
}
pub extern "C" fn curl_url() -> *mut Url {
Box::into_raw(Box::default())
}
pub extern "C" fn curl_url_cleanup(u: *mut Url) {
if !u.is_null() {
drop(unsafe { Box::from_raw(u) });
}
}
pub extern "C" fn curl_url_dup(u: *mut Url) -> *mut Url {
url(u).map_or(std::ptr::null_mut(), |u| Box::into_raw(Box::new(u.clone())))
}
pub extern "C" fn curl_url_set(u: *mut Url, what: c_int, content: *const c_char, _flags: c_uint) -> UrlCode {
let Some(u) = url(u) else {
return CURLUE_BAD_HANDLE;
};
let Some(index) = usize::try_from(what).ok().filter(|&i| i < PARTS) else {
return CURLUE_UNKNOWN_PART;
};
let value = text(content).map(|c| c.to_string_lossy().into_owned());
if what == URL {
return match value {
Some(v) if u.parse(&v) => CURLUE_OK,
Some(_) => CURLUE_MALFORMED_INPUT,
None => {
*u = Url::default();
CURLUE_OK
}
};
}
u.parts[index] = value;
CURLUE_OK
}
pub extern "C" fn curl_url_get(u: *mut Url, what: c_int, out: *mut *mut c_char, _flags: c_uint) -> UrlCode {
let Some(u) = url(u) else {
return CURLUE_BAD_HANDLE;
};
if out.is_null() {
return CURLUE_BAD_PARTPOINTER;
}
let Some(index) = usize::try_from(what).ok().filter(|&i| i < PARTS) else {
return CURLUE_UNKNOWN_PART;
};
let value = match what {
URL => u.whole(),
7 => Some(u.parts[7].clone().unwrap_or_else(|| "/".into())),
_ => u.parts[index].clone(),
};
unsafe { out.write(std::ptr::null_mut()) };
match value {
Some(v) => {
unsafe { out.write(give(v.as_bytes())) };
CURLUE_OK
}
None if what == URL => CURLUE_MALFORMED_INPUT,
None => no_part(index),
}
}
pub extern "C" fn curl_version() -> *const c_char {
c"libcurl/7.76.0 (eonacat-xs, offline)".as_ptr()
}
#[repr(C)]
pub struct VersionInfo {
age: c_int,
version: *const c_char,
version_num: c_uint,
host: *const c_char,
features: c_int,
ssl_version: *const c_char,
ssl_version_num: c_long,
libz_version: *const c_char,
protocols: *const *const c_char,
ares: *const c_char,
ares_num: c_int,
libidn: *const c_char,
iconv_ver_num: c_int,
libssh_version: *const c_char,
brotli_ver_num: c_uint,
brotli_version: *const c_char,
nghttp2_ver_num: c_uint,
nghttp2_version: *const c_char,
quic_version: *const c_char,
}
struct Shared<T>(T);
unsafe impl<T> Sync for Shared<T> {}
unsafe impl<T> Send for Shared<T> {}
pub extern "C" fn curl_version_info(_age: c_int) -> *const VersionInfo {
static PROTOCOLS: Shared<[*const c_char; 3]> = Shared([c"http".as_ptr(), c"https".as_ptr(), std::ptr::null()]);
static INFO: OnceLock<Shared<VersionInfo>> = OnceLock::new();
let null = std::ptr::null();
let info = INFO.get_or_init(|| {
Shared(VersionInfo {
age: 5,
version: c"7.76.0".as_ptr(),
version_num: 0x07_4c_00,
host: c"x86_64-pc-win32".as_ptr(),
features: 1 << 0 | 1 << 9,
ssl_version: null,
ssl_version_num: 0,
libz_version: null,
protocols: PROTOCOLS.0.as_ptr(),
ares: null,
ares_num: 0,
libidn: null,
iconv_ver_num: 0,
libssh_version: null,
brotli_ver_num: 0,
brotli_version: null,
nghttp2_ver_num: 0,
nghttp2_version: null,
quic_version: null,
})
});
&info.0
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "xcurl",
dlls: &["xcurl.dll"],
exports: vec![
hle_export!(curl_easy_cleanup),
hle_export!(curl_easy_duphandle),
hle_export!(curl_easy_escape),
hle_export!(curl_easy_getinfo),
hle_export!(curl_easy_init),
hle_export!(curl_easy_perform),
hle_export!(curl_easy_reset),
hle_export!(curl_easy_setopt),
hle_export!(curl_easy_strerror),
hle_export!(curl_easy_unescape),
hle_export!(curl_escape),
hle_export!(curl_formadd),
hle_export!(curl_formfree),
hle_export!(curl_formget),
hle_export!(curl_free),
hle_export!(curl_getdate),
hle_export!(curl_global_cleanup),
hle_export!(curl_global_init),
hle_export!(curl_global_init_mem),
hle_export!(curl_global_sslset),
hle_export!(curl_mime_addpart),
hle_export!(curl_mime_data),
hle_export!(curl_mime_data_cb),
hle_export!(curl_mime_encoder),
hle_export!(curl_mime_filedata),
hle_export!(curl_mime_filename),
hle_export!(curl_mime_free),
hle_export!(curl_mime_headers),
hle_export!(curl_mime_init),
hle_export!(curl_mime_name),
hle_export!(curl_mime_subparts),
hle_export!(curl_mime_type),
hle_export!(curl_multi_add_handle),
hle_export!(curl_multi_cleanup),
hle_export!(curl_multi_info_read),
hle_export!(curl_multi_init),
hle_export!(curl_multi_perform),
hle_export!(curl_multi_poll),
hle_export!(curl_multi_remove_handle),
hle_export!(curl_multi_setopt),
hle_export!(curl_multi_strerror),
hle_export!(curl_multi_wait),
hle_export!(curl_multi_wakeup),
hle_export!(curl_share_cleanup),
hle_export!(curl_share_init),
hle_export!(curl_share_setopt),
hle_export!(curl_share_strerror),
hle_export!(curl_slist_append),
hle_export!(curl_slist_free_all),
hle_export!(curl_unescape),
hle_export!(curl_url),
hle_export!(curl_url_cleanup),
hle_export!(curl_url_dup),
hle_export!(curl_url_get),
hle_export!(curl_url_set),
hle_export!(curl_version),
hle_export!(curl_version_info),
hle_export!(xcurl_global_init_mem),
hle_export!(xcurl_global_resume),
hle_export!(xcurl_global_set_request_limit),
hle_export!(xcurl_global_suspend),
],
}
}
File diff suppressed because it is too large. Load diff
+275
View File
@@ -0,0 +1,275 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{CStr, c_char, c_void};
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, token, with_spare,
};
use crate::hle::runtime;
pub const TITLE_PROVIDER: Guid = Guid::new(
0x973a_344e,
0x24bf,
0x4d0f,
[0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29],
);
pub const TITLE_IID: Guid = Guid::new(
0x2549_f142,
0x6419,
0x4a06,
[0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34],
);
pub const FEATURES: Guid = Guid::new(
0x8836_fe87,
0xedb9,
0x4fe3,
[0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40],
);
pub const INVITES: Guid = Guid::new(
0x0651_aae2,
0x4012,
0x4077,
[0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c],
);
pub const EVENTS: Guid = Guid::new(
0xbbfb_dcc7,
0xbfe7,
0x409b,
[0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d],
);
pub const PENDING_INVITES_IID: Guid = Guid::new(
0x014d_1cc3,
0xbcfe,
0x41ff,
[0xb2, 0xf0, 0xe1, 0xef, 0x07, 0x15, 0x58, 0x28],
);
pub const ACTIVATION_PROVIDER: Guid = Guid::new(
0x7f0f_e8b8,
0xe075,
0x49ab,
[0x9a, 0xa7, 0xa1, 0xe0, 0x65, 0x48, 0x9a, 0x9e],
);
pub const ACTIVATION_IID: Guid = Guid::new(
0x2e4f_76fe,
0x0fc7,
0x461e,
[0xab, 0x4d, 0xa4, 0x49, 0x94, 0x34, 0xc3, 0xcf],
);
pub const PROTOCOL_PROVIDER: Guid = Guid::new(
0x95fd_18d2,
0x74dd,
0x4d7c,
[0xaa, 0x1b, 0x0b, 0x51, 0x82, 0x76, 0x65, 0xd6],
);
pub const PROTOCOL_IID: Guid = Guid::new(
0x026b_010c,
0x06c3,
0x4cdd,
[0xbb, 0xcb, 0x43, 0xf2, 0x29, 0xdb, 0x1c, 0xff],
);
pub static TITLE_OBJECT: Object = Object::new("title", &TITLE_VTABLE);
pub static ACTIVATION_OBJECT: Object = Object::new("activation", &ACTIVATION_VTABLE);
pub static PROTOCOL_OBJECT: Object = Object::new("protocol activation", &PROTOCOL_VTABLE);
pub static FEATURES_OBJECT: Object = Object::new("features", &FEATURES_VTABLE);
pub static INVITES_OBJECT: Object = Object::new("invites", &INVITES_VTABLE);
pub static EVENTS_OBJECT: Object = Object::new("events", &EVENTS_VTABLE);
pub const INTERFACES: &[Interface] = &[
(TITLE_PROVIDER, TITLE_IID, &TITLE_OBJECT),
(FEATURES, FEATURES, &FEATURES_OBJECT),
(INVITES, INVITES, &INVITES_OBJECT),
(INVITES, PENDING_INVITES_IID, &INVITES_OBJECT),
(EVENTS, EVENTS, &EVENTS_OBJECT),
(ACTIVATION_PROVIDER, ACTIVATION_IID, &ACTIVATION_OBJECT),
(PROTOCOL_PROVIDER, PROTOCOL_IID, &PROTOCOL_OBJECT),
];
type This = *const Object;
extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT {
put(out, runtime::title().id)
}
extern "system" fn launch_new_game(
_: This,
exe: *const c_char,
args: *const c_char,
_user: *const c_void,
) {
let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default());
tracing::info!(exe, args, "XLaunchNewGame");
let current = runtime::main_image()
.and_then(runtime::image_path)
.unwrap_or_default();
let ours: Vec<_> = std::env::args_os().skip(1).collect();
let command = relaunch_args(ours, current.as_os_str(), &exe, &args);
#[cfg(windows)]
{
super::lifecycle::end_title(
"XLaunchNewGame",
Box::new(move || super::lifecycle::relaunch(command)),
);
loop {
std::thread::park();
}
}
#[cfg(not(windows))]
let _ = command;
}
fn relaunch_args(
ours: Vec<std::ffi::OsString>,
current: &std::ffi::OsStr,
exe: &str,
args: &str,
) -> Vec<std::ffi::OsString> {
let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect();
if !exe.is_empty()
&& let Some(slot) = out.iter_mut().find(|a| {
a.as_os_str() == current
|| std::path::absolute(a).is_ok_and(|p| p.as_os_str() == current)
})
{
*slot = exe.into();
}
if !args.trim().is_empty() {
out.push("--".into());
out.extend(split_args(args).into_iter().map(Into::into));
}
out
}
fn split_args(args: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current = String::new();
let mut quoted = false;
let mut started = false;
for c in args.chars() {
match c {
'"' => {
quoted = !quoted;
started = true;
}
c if !quoted && c.is_whitespace() => {
if started {
out.push(std::mem::take(&mut current));
started = false;
}
}
c => {
current.push(c);
started = true;
}
}
}
if started {
out.push(current);
}
out
}
const AVAILABLE: [u32; 20] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20,
];
extern "system" fn is_feature_available(_: This, feature: u32) -> bool {
AVAILABLE.contains(&feature)
}
extern "system" fn register(
_: This,
_queue: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
true
}
extern "system" fn accept_pending_invite(_: This, uri: *const c_char) -> HRESULT {
tracing::info!(
uri = text(uri).unwrap_or_default(),
"an invite accepted: none is pending offline"
);
E_INVALIDARG
}
extern "system" fn write_event(
_: This,
_user: *const c_void,
_service_config: *const c_char,
_session: *const c_char,
name: *const c_char,
_dimensions: *const c_char,
_measurements: *const c_char,
) -> HRESULT {
if !name.is_null() {
let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();
tracing::debug!(%name, "game event dropped");
}
S_OK
}
static TITLE_VTABLE: Methods<14> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
title_id as *const (),
launch_new_game as *const (),
missing::<5> as *const (),
]);
static FEATURES_VTABLE: Methods<12> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
is_feature_available as *const (),
]);
static INVITES_VTABLE: Methods<16> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
register as *const (),
unregister as *const (),
register as *const (),
unregister as *const (),
accept_pending_invite as *const (),
]);
static ACTIVATION_VTABLE: Methods<6> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
register as *const (),
unregister as *const (),
accept_pending_invite as *const (),
]);
static PROTOCOL_VTABLE: Methods<5> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
register as *const (),
unregister as *const (),
]);
static EVENTS_VTABLE: Methods<12> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
write_event as *const (),
]);
@@ -0,0 +1,346 @@
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{CStr, c_char, c_void};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use super::{
display, speech, storage, xasync, xgame, xgamesave, xgameui, xnetworking, xpackage, xstore,
xsystem, xuser,
};
use crate::hle::{HleModule};
use crate::hle_export;
pub type HRESULT = i32;
pub const S_OK: HRESULT = 0;
pub const NOT_SUPPORTED: HRESULT = 0x8007_0032_u32 as i32;
pub const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Guid {
pub data1: u32,
pub data2: u16,
pub data3: u16,
pub data4: [u8; 8],
}
impl Guid {
pub const fn new(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid {
Guid {
data1,
data2,
data3,
data4,
}
}
}
impl std::fmt::Display for Guid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let d = self.data4;
write!(
f,
"{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
self.data1, self.data2, self.data3, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]
)
}
}
#[repr(C)]
pub struct Object {
vtable: *const *const (),
area: &'static str,
slots: usize,
}
unsafe impl Sync for Object {}
impl Object {
pub const fn new<const N: usize>(area: &'static str, methods: &'static Methods<N>) -> Object {
Object {
vtable: methods.0.as_ptr(),
area,
slots: N,
}
}
}
pub struct Methods<const N: usize>(pub [*const (); N]);
unsafe impl<const N: usize> Sync for Methods<N> {}
macro_rules! spare {
($($slot:literal)*) => { [$(missing::<$slot> as *const ()),*] };
}
pub const fn with_spare<const K: usize, const N: usize>(known: [*const (); K]) -> Methods<N> {
let spare = spare!(
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
);
assert!(K <= N && N <= spare.len());
let mut table = [std::ptr::null(); N];
let mut i = 0;
while i < N {
table[i] = if i < K { known[i] } else { spare[i] };
i += 1;
}
Methods(table)
}
pub type Interface = (Guid, Guid, &'static Object);
const AREAS: &[&[Interface]] = &[
xasync::INTERFACES,
xuser::INTERFACES,
xsystem::INTERFACES,
xgame::INTERFACES,
storage::INTERFACES,
xnetworking::INTERFACES,
xpackage::INTERFACES,
display::INTERFACES,
xgamesave::INTERFACES,
xstore::INTERFACES,
xgameui::INTERFACES,
speech::INTERFACES,
ERROR_INTERFACES,
];
pub extern "system" fn add_ref(_: *const Object) -> u32 {
1
}
pub extern "system" fn missing<const SLOT: usize>(this: *const Object) -> HRESULT {
let area = unsafe { (*this).area };
tracing::warn!(
area,
slot = format_args!("{:#x}", SLOT * 8),
"runtime method not implemented"
);
xasync::E_NOTIMPL
}
pub fn put<T>(out: *mut T, value: T) -> HRESULT {
if out.is_null() {
return xasync::E_INVALIDARG;
}
unsafe { out.write(value) };
S_OK
}
pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
let len = text.len() + 1;
if buffer.is_null() || size < len {
return xasync::E_NOT_SUFFICIENT_BUFFER;
}
unsafe {
buffer.copy_from_nonoverlapping(text.as_ptr(), text.len());
buffer.add(text.len()).write(0);
}
if !used.is_null() {
unsafe { used.write(len) };
}
S_OK
}
pub fn text(s: *const c_char) -> Option<String> {
(!s.is_null()).then(|| unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned())
}
pub fn token() -> u64 {
static NEXT: AtomicU64 = AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
pub extern "system" fn XGameRuntimeInitialize() -> HRESULT {
tracing::info!("XGameRuntimeInitialize");
S_OK
}
pub extern "system" fn XGameRuntimeUninitialize() {
tracing::info!("XGameRuntimeUninitialize");
}
static RUNTIME_BUILD: AtomicU64 = AtomicU64::new(0);
pub fn runtime_build() -> u64 {
RUNTIME_BUILD.load(Ordering::Relaxed)
}
fn note_build(build: u64) {
let _ = RUNTIME_BUILD.compare_exchange(0, build, Ordering::Relaxed, Ordering::Relaxed);
eonacat_xsbox_gpu::device::note_runtime_build(build);
}
pub extern "system" fn InitializeApiImpl(version: u64, build: u64) -> HRESULT {
tracing::info!(version, build, "InitializeApiImpl");
note_build(build);
S_OK
}
pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) -> HRESULT {
tracing::info!(version, build, flags, "InitializeApiImplEx");
note_build(build);
S_OK
}
pub extern "system" fn InitializeApiImplEx2(
version: u64,
build: u64,
flags: u64,
options: *const c_void,
) -> HRESULT {
tracing::info!(version, build, flags, ?options, "InitializeApiImplEx2");
note_build(build);
S_OK
}
pub extern "system" fn UninitializeApiImpl() {
tracing::info!("UninitializeApiImpl");
}
pub extern "system" fn QueryApiImpl(
provider: *const Guid,
iid: *const Guid,
out: *mut *mut c_void,
) -> HRESULT {
static QUERIED: Mutex<Vec<(Guid, Guid, u64)>> = Mutex::new(Vec::new());
if out.is_null() {
return E_POINTER;
}
let (Some(&provider), Some(&iid)) = (unsafe { provider.as_ref() }, unsafe { iid.as_ref() })
else {
return NOT_SUPPORTED;
};
#[cfg(feature = "diagnostics")]
if tracing::enabled!(tracing::Level::DEBUG) {
static CALLS: Mutex<Vec<String>> = Mutex::new(Vec::new());
let from = super::kernel::callers();
let mut calls = CALLS.lock().unwrap_or_else(|e| e.into_inner());
if !calls.contains(&from) {
tracing::debug!(%provider, %iid, %from, "runtime call");
calls.push(from);
}
}
let found = AREAS
.iter()
.flat_map(|area| area.iter())
.find(|(p, i, _)| (*p, *i) == (provider, iid));
if let Some(&(_, _, object)) = found {
unsafe { out.write((object as *const Object).cast_mut().cast()) };
return S_OK;
}
let mut queried = QUERIED.lock().unwrap_or_else(|e| e.into_inner());
match queried.iter_mut().find(|(p, i, _)| (*p, *i) == (provider, iid)) {
None => {
queried.push((provider, iid, 1));
tracing::warn!(%provider, %iid, "runtime API area not implemented");
}
Some((_, _, calls)) => {
*calls += 1;
#[cfg(feature = "diagnostics")]
if calls.is_power_of_two() {
tracing::info!(%provider, %iid, calls = *calls, "runtime API area not implemented, asked again");
}
}
}
NOT_SUPPORTED
}
pub extern "system" fn XErrorReport(hr: HRESULT, message: *const c_char) {
let text = if message.is_null() {
"".into()
} else {
unsafe { CStr::from_ptr(message) }.to_string_lossy()
};
tracing::warn!(hr = format_args!("{:#010x}", hr as u32), message = %text, "XErrorReport");
let callback = *ERROR_CALLBACK.lock().unwrap_or_else(|e| e.into_inner());
if let Some((callback, context)) = callback {
let callback: ErrorCallback = unsafe { std::mem::transmute(callback) };
let message = if message.is_null() {
c"".as_ptr()
} else {
message
};
callback(hr, message, context as *mut c_void);
}
}
type ErrorCallback = extern "system" fn(HRESULT, *const c_char, *mut c_void) -> bool;
static ERROR_CALLBACK: Mutex<Option<(usize, usize)>> = Mutex::new(None);
pub const ERROR_AREA: Guid = Guid::new(
0x8ca4_67f7,
0x22e8,
0x4096,
[0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8],
);
static ERROR_OBJECT: Object = Object::new("errors", &ERROR_METHODS);
const ERROR_INTERFACES: &[Interface] = &[(ERROR_AREA, ERROR_AREA, &ERROR_OBJECT)];
extern "system" fn error_report(_: *const Object, hr: HRESULT, message: *const c_char) {
XErrorReport(hr, message);
}
extern "system" fn error_set_callback(
_: *const Object,
callback: Option<ErrorCallback>,
context: *mut c_void,
) {
*ERROR_CALLBACK.lock().unwrap_or_else(|e| e.into_inner()) =
callback.map(|c| (c as usize, context as usize));
}
extern "system" fn error_set_options(_: *const Object, debugger: u32, no_debugger: u32) {
tracing::info!(debugger, no_debugger, "XErrorSetOptions: logged only");
}
static ERROR_METHODS: Methods<6> = Methods([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
error_report as *const (),
error_set_callback as *const (),
error_set_options as *const (),
]);
pub(crate) fn module() -> HleModule {
HleModule {
name: "xgameruntime",
dlls: &["xgameruntime.dll"],
exports: vec![
hle_export!(XGameRuntimeInitialize),
hle_export!(XGameRuntimeUninitialize),
hle_export!(InitializeApiImpl),
hle_export!(InitializeApiImplEx),
hle_export!(InitializeApiImplEx2),
hle_export!(UninitializeApiImpl),
hle_export!(QueryApiImpl),
hle_export!(XErrorReport),
],
}
}
File diff suppressed because it is too large. Load diff
+636
View File
@@ -0,0 +1,636 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock, E_ABORT};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, with_spare,
};
pub const PROVIDER: Guid = Guid::new(
0xdfcd_4649,
0x4ff8,
0x4043,
[0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0],
);
pub const IID_2026: Guid = Guid::new(
0xeaf6_69df,
0x5542,
0x4590,
[0x99, 0xa3, 0x8d, 0xc0, 0x61, 0xf8, 0x37, 0xcc],
);
pub static OBJECT: Object = Object::new("game ui", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)];
type This = *const Object;
static PROFILE: u8 = 0;
static TEXT: u8 = 0;
extern "system" fn profile_card_async(
_: This,
block: *mut AsyncBlock,
_user: *const c_void,
xuid: u64,
) -> HRESULT {
tracing::info!(xuid, "profile card: nothing to show");
xasync::finished(block, (&raw const PROFILE).cast(), S_OK)
}
extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast())
}
extern "system" fn text_entry_async(
_: This,
block: *mut AsyncBlock,
title: *const c_char,
description: *const c_char,
default: *const c_char,
scope: u32,
max_length: u32,
) -> HRESULT {
let [title, description, default] =
[title, description, default].map(|t| text(t).unwrap_or_default());
let max_length = max_length_for(scope, max_length);
let password = scope == PASSWORD;
tracing::info!(title, description, max_length, password, "text entry");
xasync::pending_with(block, (&raw const TEXT).cast(), move || {
match ask(&title, &description, &default, max_length, password) {
Some(typed) => {
tracing::info!(length = typed.chars().count(), "text entry: done");
let mut bytes = limit(&typed, max_length).into_bytes();
bytes.push(0);
Ok(bytes)
}
None => {
tracing::info!("text entry: cancelled");
Err(E_ABORT)
}
}
})
}
extern "system" fn text_entry_size(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT {
let mut size = 0;
let hr = xasync::XAsyncGetResultSize(block, &mut size);
if hr < 0 {
return hr;
}
put(out, size as u32)
}
extern "system" fn text_entry_result(
_: This,
block: *mut AsyncBlock,
size: u32,
buffer: *mut c_char,
used: *mut u32,
) -> HRESULT {
let mut written = 0;
let identity = (&raw const TEXT).cast();
let hr = xasync::XAsyncGetResult(block, identity, size as usize, buffer.cast(), &mut written);
if hr < 0 || used.is_null() {
return hr;
}
put(used, written as u32)
}
static MESSAGE: u8 = 0;
static ERROR: u8 = 0;
static CLOSED: u8 = 0;
static PICKER: u8 = 0;
#[allow(clippy::too_many_arguments)]
extern "system" fn message_dialog_async(
_: This,
block: *mut AsyncBlock,
title: *const c_char,
content: *const c_char,
first: *const c_char,
second: *const c_char,
third: *const c_char,
default: u32,
cancel: u32,
) -> HRESULT {
let [title, content] = [title, content].map(|t| text(t).unwrap_or_default());
let buttons: Vec<(u32, String)> = [first, second, third]
.into_iter()
.zip(0..)
.filter_map(|(label, i)| text(label).filter(|l| !l.is_empty()).map(|l| (i, l)))
.collect();
if buttons.is_empty() {
return xasync::E_INVALIDARG;
}
tracing::info!(title, buttons = buttons.len(), "message dialog");
xasync::pending_with(block, (&raw const MESSAGE).cast(), move || {
let chosen = choose(&title, &content, &buttons, default, cancel);
tracing::info!(chosen, "message dialog: done");
Ok(chosen.to_le_bytes().to_vec())
})
}
extern "system" fn message_dialog_result(
_: This,
block: *mut AsyncBlock,
out: *mut u32,
) -> HRESULT {
xasync::result(block, (&raw const MESSAGE).cast(), out)
}
extern "system" fn error_dialog_async(
_: This,
block: *mut AsyncBlock,
error: HRESULT,
context: *const c_char,
) -> HRESULT {
let context = text(context).unwrap_or_default();
tracing::warn!(
error = format_args!("{:#010x}", error as u32),
context,
"error dialog"
);
xasync::pending_with(block, (&raw const ERROR).cast(), move || {
show_error(error, &context);
Ok(Vec::new())
})
}
extern "system" fn error_dialog_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const ERROR).cast(), 0, none, none.cast())
}
extern "system" fn achievements_async(
_: This,
block: *mut AsyncBlock,
_user: *const c_void,
title_id: u32,
) -> HRESULT {
tracing::info!(title_id, "achievements: nothing to show");
xasync::finished(block, (&raw const CLOSED).cast(), S_OK)
}
fn dismissed(block: *mut AsyncBlock, what: &str) -> HRESULT {
tracing::info!(what, "a page for other players: dismissed offline");
xasync::finished(block, (&raw const CLOSED).cast(), E_ABORT)
}
#[allow(clippy::too_many_arguments)]
extern "system" fn send_invite_async(
_: This,
block: *mut AsyncBlock,
_user: *const c_void,
_configuration: *const c_char,
_template: *const c_char,
_session: *const c_char,
_text: *const c_char,
_context: *const c_char,
) -> HRESULT {
dismissed(block, "send game invite")
}
extern "system" fn activity_invite_async(
_: This,
block: *mut AsyncBlock,
_user: *const c_void,
) -> HRESULT {
dismissed(block, "multiplayer activity invite")
}
extern "system" fn state_share_async(
_: This,
block: *mut AsyncBlock,
_user: *const c_void,
_link: *const c_char,
) -> HRESULT {
dismissed(block, "state share")
}
extern "system" fn closed_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const CLOSED).cast(), 0, none, none.cast())
}
#[allow(clippy::too_many_arguments)]
extern "system" fn player_picker_async(
_: This,
block: *mut AsyncBlock,
_user: *const c_void,
_prompt: *const c_char,
_count: u32,
_players: *const u64,
_preselected_count: u32,
_preselected: *const u64,
minimum: u32,
_maximum: u32,
) -> HRESULT {
let result = if minimum == 0 {
Ok(Vec::new())
} else {
Err(E_ABORT)
};
xasync::finished_with(block, (&raw const PICKER).cast(), result)
}
extern "system" fn player_picker_count(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT {
let mut size = 0;
let hr = xasync::XAsyncGetResultSize(block, &mut size);
if hr < 0 {
return hr;
}
put(out, (size / 8) as u32)
}
extern "system" fn player_picker_result(
_: This,
block: *mut AsyncBlock,
count: u32,
players: *mut u64,
used: *mut u32,
) -> HRESULT {
let mut written = 0;
let identity = (&raw const PICKER).cast();
let hr = xasync::XAsyncGetResult(
block,
identity,
count as usize * 8,
players.cast(),
&mut written,
);
if hr < 0 || used.is_null() {
return hr;
}
put(used, (written / 8) as u32)
}
extern "system" fn notification_position(_: This, _position: u32) -> HRESULT {
S_OK
}
extern "system" fn set_ui_callbacks(_: This, _callbacks: *const c_void, system: bool) -> HRESULT {
tracing::info!(system, "XGameUiSetUiCallbacks: our dialogs show");
S_OK
}
fn choose(title: &str, content: &str, buttons: &[(u32, String)], default: u32, cancel: u32) -> u32 {
dialog::choose(title, content, buttons, default, cancel)
}
fn show_error(error: HRESULT, context: &str) {
dialog::show_error(error, context);
}
const MAX_LENGTH: u32 = 1024;
const PASSWORD: u32 = 31;
fn max_length_for(scope: u32, max: u32) -> u32 {
if max == 0 || scope == PASSWORD {
MAX_LENGTH
} else {
max.min(MAX_LENGTH)
}
}
fn limit(typed: &str, max: u32) -> String {
typed.chars().take(max as usize).collect()
}
fn ask(title: &str, description: &str, default: &str, max: u32, password: bool) -> Option<String> {
dialog::ask(title, description, default, max, password)
}
mod dialog {
use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::SetFocus;
use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, DLGTEMPLATE};
const EDIT: i32 = 100;
const EM_SETSEL: u32 = 0xb1;
const EM_LIMITTEXT: u32 = 0xc5;
struct Entry {
max: u32,
typed: Option<String>,
}
#[allow(dead_code)]
pub(super) fn ask(
title: &str,
description: &str,
default: &str,
max: u32,
password: bool,
) -> Option<String> {
let mut t: Vec<u16> = Vec::new();
fn dword(t: &mut Vec<u16>, v: u32) {
t.extend([v as u16, (v >> 16) as u16]);
}
fn text(t: &mut Vec<u16>, s: &str) {
t.extend(s.encode_utf16().filter(|&c| c != 0));
t.push(0);
}
let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU;
let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32;
dword(&mut t, style | flags);
dword(&mut t, wm::WS_EX_TOPMOST);
t.extend([4, 0, 0, 240, 62, 0, 0]);
text(&mut t, title);
let mut item = |style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str| {
if t.len() % 2 == 1 {
t.push(0);
}
dword(&mut t, wm::WS_CHILD | wm::WS_VISIBLE | style);
dword(&mut t, 0);
t.extend(rect);
t.extend([id, 0xffff, class]);
text(&mut t, caption);
t.push(0);
};
let (button, edit, label) = (0x80, 0x81, 0x82);
let tab = wm::WS_TABSTOP;
item(0, [7, 7, 226, 10], 0xffff, label, description);
let mut edit_style = wm::WS_BORDER | tab | wm::ES_AUTOHSCROLL as u32;
if password {
edit_style |= wm::ES_PASSWORD as u32;
}
item(edit_style, [7, 20, 226, 12], EDIT as u16, edit, default);
let ok = wm::BS_DEFPUSHBUTTON as u32 | tab;
item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK");
let cancel = wm::BS_PUSHBUTTON as u32 | tab;
item(
cancel,
[183, 40, 50, 14],
wm::IDCANCEL as u16,
button,
"Cancel",
);
let template: Vec<u32> = t
.chunks(2)
.map(|c| u32::from(c[0]) | u32::from(c.get(1).copied().unwrap_or(0)) << 16)
.collect();
let mut entry = Entry { max, typed: None };
unsafe {
wm::DialogBoxIndirectParamW(
GetModuleHandleW(std::ptr::null()),
template.as_ptr().cast::<DLGTEMPLATE>(),
std::ptr::null_mut(),
Some(procedure),
(&raw mut entry) as LPARAM,
);
}
entry.typed
}
extern "system" fn procedure(
dialog: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> isize {
unsafe {
let edit = wm::GetDlgItem(dialog, EDIT);
match message {
wm::WM_INITDIALOG => {
wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam);
let entry = &*(lparam as *const Entry);
wm::SendMessageW(edit, EM_LIMITTEXT, entry.max as WPARAM, 0);
wm::SendMessageW(edit, EM_SETSEL, 0, -1);
SetFocus(edit);
0
}
wm::WM_COMMAND => {
let user_data = wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA);
if user_data == 0 {
return 0;
}
let entry = &mut *(user_data as *mut Entry);
match (wparam & 0xffff) as i32 {
wm::IDOK => {
let mut buffer =
vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1];
let n =
wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32);
entry.typed =
Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize]));
wm::EndDialog(dialog, 1);
}
wm::IDCANCEL => {
wm::EndDialog(dialog, 0);
}
_ => return 0,
}
1
}
_ => 0,
}
}
}
struct Template(Vec<u16>);
impl Template {
fn new(title: &str, items: u16, size: [u16; 2]) -> Template {
let mut t = Template(Vec::new());
let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU;
let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32;
t.dword(style | flags);
t.dword(wm::WS_EX_TOPMOST);
t.0.extend([items, 0, 0, size[0], size[1], 0, 0]);
t.text(title);
t
}
fn dword(&mut self, v: u32) {
self.0.extend([v as u16, (v >> 16) as u16]);
}
fn text(&mut self, s: &str) {
self.0.extend(s.encode_utf16().filter(|&c| c != 0));
self.0.push(0);
}
fn item(&mut self, style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str) {
if self.0.len() % 2 == 1 {
self.0.push(0);
}
self.dword(wm::WS_CHILD | wm::WS_VISIBLE | style);
self.dword(0);
self.0.extend(rect);
self.0.extend([id, 0xffff, class]);
self.text(caption);
self.0.push(0);
}
fn words(&self) -> Vec<u32> {
self.0
.chunks(2)
.map(|c| u32::from(c[0]) | (u32::from(c.get(1).copied().unwrap_or(0)) << 16))
.collect()
}
}
const FIRST_BUTTON: i32 = 1000;
struct Choice {
default: u32,
cancel: u32,
}
#[allow(dead_code)]
pub(super) fn choose(
title: &str,
content: &str,
buttons: &[(u32, String)],
default: u32,
cancel: u32,
) -> u32 {
const WIDTH: u16 = 260;
const BUTTON: u16 = 70;
let mut t = Template::new(title, 1 + buttons.len() as u16, [WIDTH, 96]);
t.item(0, [7, 7, WIDTH - 14, 60], 0xffff, 0x82, content);
let mut x = WIDTH - 7 - (BUTTON + 4) * buttons.len() as u16 + 4;
for (number, label) in buttons {
let kind = if *number == default {
wm::BS_DEFPUSHBUTTON
} else {
wm::BS_PUSHBUTTON
};
let id = (FIRST_BUTTON + *number as i32) as u16;
t.item(
kind as u32 | wm::WS_TABSTOP,
[x, 74, BUTTON, 14],
id,
0x80,
label,
);
x += BUTTON + 4;
}
let template = t.words();
let mut choice = Choice { default, cancel };
let ended = unsafe {
wm::DialogBoxIndirectParamW(
GetModuleHandleW(std::ptr::null()),
template.as_ptr().cast::<DLGTEMPLATE>(),
std::ptr::null_mut(),
Some(buttons_procedure),
(&raw mut choice) as LPARAM,
)
};
u32::try_from(ended).unwrap_or(cancel)
}
extern "system" fn buttons_procedure(
dialog: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> isize {
unsafe {
match message {
wm::WM_INITDIALOG => {
wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam);
let choice = &*(lparam as *const Choice);
let default = wm::GetDlgItem(dialog, FIRST_BUTTON + choice.default as i32);
if default.is_null() {
return 1;
}
SetFocus(default);
0
}
wm::WM_COMMAND => {
let user_data = wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA);
if user_data == 0 {
return 0;
}
let choice = &*(user_data as *const Choice);
match (wparam & 0xffff) as i32 {
id @ FIRST_BUTTON..=1002 => {
wm::EndDialog(dialog, (id - FIRST_BUTTON) as isize);
}
wm::IDCANCEL => {
wm::EndDialog(dialog, choice.cancel as isize);
}
_ => return 0,
}
1
}
_ => 0,
}
}
}
#[allow(dead_code)]
pub(super) fn show_error(error: i32, context: &str) {
let text = if context.is_empty() {
format!("Error {:#010x}", error as u32)
} else {
format!("{context}\n\nError {:#010x}", error as u32)
};
let wide = |s: &str| s.encode_utf16().chain([0]).collect::<Vec<u16>>();
let (text, caption) = (wide(&text), wide("Error"));
let style = wm::MB_OK | wm::MB_ICONERROR | wm::MB_TOPMOST | wm::MB_SETFOREGROUND;
unsafe { wm::MessageBoxW(std::ptr::null_mut(), text.as_ptr(), caption.as_ptr(), style) };
}
}
static VTABLE: Methods<59> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
message_dialog_async as *const (),
message_dialog_result as *const (),
send_invite_async as *const (),
closed_result as *const (),
profile_card_async as *const (),
profile_card_result as *const (),
achievements_async as *const (),
closed_result as *const (),
player_picker_async as *const (),
player_picker_count as *const (),
player_picker_result as *const (),
error_dialog_async as *const (),
error_dialog_result as *const (),
notification_position as *const (),
text_entry_async as *const (),
text_entry_size as *const (),
text_entry_result as *const (),
missing::<20> as *const (),
missing::<21> as *const (),
missing::<22> as *const (),
missing::<23> as *const (),
missing::<24> as *const (),
missing::<25> as *const (),
missing::<26> as *const (),
missing::<27> as *const (),
missing::<28> as *const (),
missing::<29> as *const (),
activity_invite_async as *const (),
closed_result as *const (),
missing::<32> as *const (),
missing::<33> as *const (),
missing::<34> as *const (),
missing::<35> as *const (),
missing::<36> as *const (),
missing::<37> as *const (),
missing::<38> as *const (),
missing::<39> as *const (),
state_share_async as *const (),
closed_result as *const (),
set_ui_callbacks as *const (),
missing::<43> as *const (),
missing::<44> as *const (),
missing::<45> as *const (),
missing::<46> as *const (),
missing::<47> as *const (),
missing::<48> as *const (),
missing::<49> as *const (),
missing::<50> as *const (),
]);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,207 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put, text, token, with_spare,
};
pub const PROVIDER: Guid = Guid::new(
0x37e5_6907,
0x2f10,
0x41e8,
[0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a],
);
pub const IID_2026: Guid = Guid::new(
0xbf23_46b2,
0x39af,
0x4658,
[0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3],
);
pub static OBJECT: Object = Object::new("networking", &VTABLE);
pub const INTERFACES: &[Interface] =
&[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
pub const UNREACHABLE: HRESULT = 0x8007_04CF_u32 as i32;
const UDP_PORT: u16 = 3074;
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnectivityHint {
pub level: u32,
pub cost: u32,
pub interface_type: u32,
pub initialized: bool,
pub approaching_data_limit: bool,
pub over_data_limit: bool,
pub roaming: bool,
}
const OFFLINE: ConnectivityHint = ConnectivityHint {
level: 1,
cost: 0,
interface_type: 0,
initialized: true,
approaching_data_limit: false,
over_data_limit: false,
roaming: false,
};
type This = *const Object;
extern "system" fn udp_port(_: This, out: *mut u16) -> HRESULT {
put(out, UDP_PORT)
}
static PORT: u8 = 0;
extern "system" fn udp_port_async(_: This, block: *mut AsyncBlock) -> HRESULT {
xasync::finished_with(block, (&raw const PORT).cast(), Ok(xasync::bytes(UDP_PORT)))
}
extern "system" fn udp_port_result(_: This, block: *mut AsyncBlock, out: *mut u16) -> HRESULT {
xasync::result(block, (&raw const PORT).cast(), out)
}
static SECURITY: u8 = 0;
fn wide(text: *const u16) -> Option<String> {
(!text.is_null()).then(|| unsafe {
let len = (0..).take_while(|&i| *text.add(i) != 0).count();
String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
})
}
extern "system" fn security_info_async(
_: This,
url: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::debug!(
url = text(url).unwrap_or_default(),
"security information: offline"
);
xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE)
}
extern "system" fn security_info_utf16_async(
_: This,
url: *const u16,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::debug!(
url = wide(url).unwrap_or_default(),
"security information (utf16): offline"
);
xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE)
}
extern "system" fn security_info_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
xasync::XAsyncGetResultSize(block, out)
}
extern "system" fn security_info_result(
_: This,
block: *mut AsyncBlock,
size: usize,
used: *mut usize,
buffer: *mut u8,
_info: *mut *const c_void,
) -> HRESULT {
xasync::XAsyncGetResult(
block,
(&raw const SECURITY).cast(),
size,
buffer.cast(),
used,
)
}
extern "system" fn verify_certificate(
_: This,
_request: *mut c_void,
_info: *const c_void,
) -> HRESULT {
UNREACHABLE
}
extern "system" fn connectivity_hint(_: This, out: *mut ConnectivityHint) -> HRESULT {
put(out, OFFLINE)
}
extern "system" fn register(
_: This,
_queue: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
true
}
static SETTINGS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
extern "system" fn query_setting(_: This, setting: u32, out: *mut u64) -> HRESULT {
match SETTINGS.get(setting as usize) {
Some(value) => put(out, value.load(std::sync::atomic::Ordering::Relaxed)),
None => xasync::E_INVALIDARG,
}
}
extern "system" fn set_setting(_: This, setting: u32, value: u64) -> HRESULT {
match SETTINGS.get(setting as usize) {
Some(kept) => {
kept.store(value, std::sync::atomic::Ordering::Relaxed);
super::xgameruntime::S_OK
}
None => xasync::E_INVALIDARG,
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TcpQueueStatistics {
pub queued: u64,
pub peak: u64,
pub total: u64,
pub dropped_over_max: u64,
pub dropped_on_failure: u64,
}
extern "system" fn query_statistics(_: This, kind: u32, out: *mut TcpQueueStatistics) -> HRESULT {
if kind > 2 {
return xasync::E_INVALIDARG;
}
put(out, TcpQueueStatistics::default())
}
static VTABLE: Methods<29> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
udp_port as *const (),
udp_port_async as *const (),
udp_port_result as *const (),
register as *const (),
unregister as *const (),
security_info_async as *const (),
security_info_size as *const (),
security_info_result as *const (),
security_info_utf16_async as *const (),
security_info_size as *const (),
security_info_result as *const (),
verify_certificate as *const (),
connectivity_hint as *const (),
register as *const (),
unregister as *const (),
query_setting as *const (),
set_setting as *const (),
query_statistics as *const (),
]);
+454
View File
@@ -0,0 +1,454 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use std::path::Path;
use std::sync::OnceLock;
use super::xasync::{self, AsyncBlock};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text,
token, with_spare,
};
use crate::hle::runtime;
pub const PROVIDER: Guid = Guid::new(
0xaf40_6016,
0xe850,
0x4aa8,
[0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e],
);
pub const IID_2026: Guid = Guid::new(
0x0b9d_556e,
0xab70,
0x43f4,
[0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40],
);
pub static OBJECT: Object = Object::new("package", &VTABLE);
pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)];
pub const NO_PACKAGE: HRESULT = 0x8924_5208_u32 as i32;
pub fn identifier() -> String {
format!("{:08X}", runtime::title().id)
}
fn is_ours(id: *const c_char) -> bool {
text(id).is_some_and(|id| id == identifier())
}
fn package_bytes() -> u64 {
fn size(dir: &Path) -> u64 {
let Ok(entries) = std::fs::read_dir(dir) else {
return 0;
};
entries
.flatten()
.map(|e| match e.metadata() {
Ok(m) if m.is_dir() => size(&e.path()),
Ok(m) => m.len(),
Err(_) => 0,
})
.sum()
}
static BYTES: OnceLock<u64> = OnceLock::new();
static STARTED: std::sync::Once = std::sync::Once::new();
STARTED.call_once(|| {
let folder = runtime::main_image()
.and_then(runtime::image_path)
.and_then(|exe| exe.parent().map(Path::to_path_buf));
let counted = std::thread::Builder::new().name("package size".into()).spawn(move || {
let _ = BYTES.set(folder.as_deref().map_or(0, size));
});
if counted.is_err() {
let _ = BYTES.set(0);
}
});
BYTES.get().copied().unwrap_or(0)
}
type This = *const Object;
extern "system" fn current_identifier(_: This, size: usize, buffer: *mut u8) -> HRESULT {
package_bytes();
put_string(&identifier(), size, buffer, std::ptr::null_mut())
}
extern "system" fn is_packaged(_: This) -> bool {
true
}
static MONITOR: u8 = 0;
fn monitor() -> *const c_void {
(&raw const MONITOR).cast()
}
extern "system" fn create_monitor(
_: This,
id: *const c_char,
_selector_count: u32,
_selectors: *const c_void,
_interval_ms: u32,
_queue: *const c_void,
out: *mut *const c_void,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
put(out, monitor())
}
extern "system" fn close_monitor(_: This, _: *const c_void) {}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Progress {
pub total_bytes: u64,
pub installed_bytes: u64,
pub launch_bytes: u64,
pub launchable: bool,
pub completed: bool,
}
extern "system" fn progress(_: This, _: *const c_void, out: *mut Progress) {
let bytes = package_bytes();
put(
out,
Progress {
total_bytes: bytes,
installed_bytes: bytes,
launch_bytes: bytes,
launchable: true,
completed: true,
},
);
}
extern "system" fn register_progress(
_: This,
_monitor: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
extern "system" fn unregister_progress(
_: This,
_monitor: *const c_void,
_token: u64,
_wait: bool,
) -> bool {
true
}
extern "system" fn update_monitor(_: This, _monitor: *const c_void) -> bool {
false
}
extern "system" fn register_installed(
_: This,
_queue: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
extern "system" fn unregister_installed(_: This, _token: u64, _wait: bool) -> bool {
true
}
extern "system" fn find_availability(
_: This,
id: *const c_char,
_selector_count: u32,
_selectors: *const c_void,
out: *mut u32,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
put(out, 0)
}
extern "system" fn change_order(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
) -> HRESULT {
if is_ours(id) { S_OK } else { NO_PACKAGE }
}
static INSTALL: u8 = 0;
extern "system" fn install_chunks_async(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
_interval_ms: u32,
_suppress_confirmation: bool,
block: *mut AsyncBlock,
) -> HRESULT {
let result = if is_ours(id) {
Ok(xasync::bytes(monitor()))
} else {
Err(NO_PACKAGE)
};
xasync::finished_with(block, (&raw const INSTALL).cast(), result)
}
extern "system" fn install_chunks_result(
_: This,
block: *mut AsyncBlock,
out: *mut *const c_void,
) -> HRESULT {
xasync::result(block, (&raw const INSTALL).cast(), out)
}
extern "system" fn estimate_download(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
bytes: *mut u64,
confirm: *mut bool,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
if !confirm.is_null() {
unsafe { confirm.write(false) };
}
put(bytes, 0)
}
extern "system" fn uninstall_chunks(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
) -> HRESULT {
if is_ours(id) { S_OK } else { NO_PACKAGE }
}
extern "system" fn mount_path(_: This, _: *const c_void, _: usize, _: *mut u8) -> HRESULT {
xasync::E_INVALIDARG
}
extern "system" fn close_mount(_: This, _: *const c_void) {}
extern "system" fn uninstall_package(_: This, id: *const c_char) -> bool {
tracing::info!(
id = text(id).unwrap_or_default(),
"package uninstall refused"
);
false
}
static MOUNT: u8 = 0;
extern "system" fn mount_async(_: This, id: *const c_char, block: *mut AsyncBlock) -> HRESULT {
tracing::info!(
id = text(id).unwrap_or_default(),
"package mount: not installed"
);
xasync::finished(block, (&raw const MOUNT).cast(), NO_PACKAGE)
}
extern "system" fn mount_result(
_: This,
block: *mut AsyncBlock,
out: *mut *const c_void,
) -> HRESULT {
xasync::result(block, (&raw const MOUNT).cast(), out)
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct Details {
pub identifier: *const c_char,
pub version: [u16; 4],
pub kind: u32,
pub display_name: *const c_char,
pub description: *const c_char,
pub publisher: *const c_char,
pub store_id: *const c_char,
pub installing: bool,
pub index: u32,
pub count: u32,
pub age_restricted: bool,
pub title_id: *const c_char,
}
type EnumerationCallback = extern "system" fn(*mut c_void, *const Details) -> bool;
extern "system" fn enumerate(
_: This,
kind: u32,
_scope: u32,
context: *mut c_void,
callback: *const c_void,
) -> HRESULT {
if kind != 0 || callback.is_null() {
tracing::debug!(kind, "packages enumerated: none");
return S_OK;
}
let title = runtime::title();
let text = |s: String| std::ffi::CString::new(s).unwrap_or_default();
let (identifier, store_id, title_id, empty) =
(text(identifier()), text(title.store_id.clone()), text(format!("{:08X}", title.id)), text(String::new()));
let details = Details {
identifier: identifier.as_ptr(),
version: [0; 4],
kind: 0,
display_name: empty.as_ptr(),
description: empty.as_ptr(),
publisher: empty.as_ptr(),
store_id: store_id.as_ptr(),
installing: false,
index: 0,
count: 1,
age_restricted: false,
title_id: title_id.as_ptr(),
};
let callback: EnumerationCallback = unsafe { std::mem::transmute(callback) };
callback(context, &details);
S_OK
}
pub fn user_locale() -> String {
#[cfg(windows)]
{
use windows_sys::Win32::Globalization::GetUserDefaultLocaleName;
let mut name = [0u16; 85];
let len = unsafe { GetUserDefaultLocaleName(name.as_mut_ptr(), name.len() as i32) };
if len > 1 {
return String::from_utf16_lossy(&name[..len as usize - 1]);
}
}
"en-US".into()
}
extern "system" fn get_user_locale(_: This, size: usize, buffer: *mut u8) -> HRESULT {
put_string(&user_locale(), size, buffer, std::ptr::null_mut())
}
extern "system" fn enumerate_chunk_availability(
_: This,
id: *const c_char,
_kind: u32,
_context: *mut c_void,
_callback: *const c_void,
) -> HRESULT {
if is_ours(id) { S_OK } else { NO_PACKAGE }
}
extern "system" fn install_chunks(
_: This,
id: *const c_char,
_count: u32,
_selectors: *const c_void,
_interval_ms: u32,
_suppress_confirmation: bool,
_queue: *const c_void,
out: *mut *const c_void,
) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
put(out, monitor())
}
extern "system" fn mount_path_size(_: This, _: *const c_void, _: *mut usize) -> HRESULT {
xasync::E_INVALIDARG
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WriteStats {
pub interval: u64,
pub budget: u64,
pub elapsed: u64,
pub bytes_written: u64,
}
extern "system" fn write_stats(_: This, out: *mut WriteStats) -> HRESULT {
put(out, WriteStats { interval: 300, budget: 1 << 40, elapsed: 0, bytes_written: 0 })
}
extern "system" fn uninstall_uwp_instance(_: This, name: *const c_char) -> HRESULT {
tracing::info!(name = text(name).unwrap_or_default(), "UWP instance uninstall: none installed");
NO_PACKAGE
}
extern "system" fn enumerate_features(
_: This,
id: *const c_char,
_context: *mut c_void,
_callback: *const c_void,
) -> HRESULT {
if is_ours(id) { S_OK } else { NO_PACKAGE }
}
extern "system" fn package_kind(_: This, id: *const c_char, out: *mut u32) -> HRESULT {
if !is_ours(id) {
return NO_PACKAGE;
}
put(out, 0u32)
}
static VTABLE: Methods<50> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
current_identifier as *const (),
is_packaged as *const (),
create_monitor as *const (),
close_monitor as *const (),
progress as *const (),
update_monitor as *const (),
register_progress as *const (),
unregister_progress as *const (),
get_user_locale as *const (),
find_availability as *const (),
enumerate_chunk_availability as *const (),
change_order as *const (),
install_chunks as *const (),
install_chunks_async as *const (),
install_chunks_result as *const (),
estimate_download as *const (),
uninstall_chunks as *const (),
missing::<20> as *const (),
missing::<21> as *const (),
unregister_installed as *const (),
missing::<23> as *const (),
mount_path_size as *const (),
mount_path as *const (),
close_mount as *const (),
missing::<27> as *const (),
missing::<28> as *const (),
missing::<29> as *const (),
write_stats as *const (),
missing::<31> as *const (),
uninstall_uwp_instance as *const (),
enumerate_features as *const (),
uninstall_package as *const (),
missing::<35> as *const (),
missing::<36> as *const (),
mount_async as *const (),
mount_result as *const (),
enumerate as *const (),
register_installed as *const (),
package_kind as *const (),
]);
+534
View File
@@ -0,0 +1,534 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL, E_INVALIDARG};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text,
token, with_spare,
};
use super::xpackage;
use crate::hle::runtime;
pub const PROVIDER: Guid = Guid::new(
0x0dd1_12ac,
0x7c24,
0x448c,
[0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c],
);
pub const IID_2026: Guid = Guid::new(
0xb09d_803c,
0x2414,
0x4a05,
[0x82, 0xc6, 0x66, 0xdf, 0xdc, 0x9e, 0x9a, 0x44],
);
pub const DURABLES_IID: Guid = Guid::new(
0x2d42_fea5,
0xe71d,
0x4b76,
[0x97, 0xcd, 0xc5, 0x0a, 0xfb, 0xb3, 0xae, 0x5d],
);
pub const STORE_ID_IID: Guid = Guid::new(
0x5c48_dedf,
0x0b67,
0x4492,
[0xa4, 0xb5, 0x68, 0x29, 0xb8, 0xe7, 0x96, 0xe1],
);
pub const AVAILABILITY_IID: Guid = Guid::new(
0x60b0_9f4e,
0x1b85,
0x45b1,
[0x82, 0x6c, 0x16, 0x91, 0x18, 0xe2, 0x30, 0xe1],
);
pub static OBJECT: Object = Object::new("store", &VTABLE);
pub const INTERFACES: &[Interface] = &[
(PROVIDER, IID_2026, &OBJECT),
(PROVIDER, DURABLES_IID, &OBJECT),
(PROVIDER, STORE_ID_IID, &OBJECT),
(PROVIDER, AVAILABILITY_IID, &OBJECT),
];
pub const NETWORK_ERROR: HRESULT = 0x8924_5301_u32 as i32;
type This = *const Object;
type Handle = *const c_void;
static CONTEXT: u8 = 0;
static QUERY: u8 = 0;
static VALID: u8 = 0;
static INVALID: u8 = 0;
fn handle(of: &'static u8) -> Handle {
(of as *const u8).cast()
}
static FAILED: u8 = 0;
static QUERY_CALL: u8 = 0;
static LICENSE_CALL: u8 = 0;
static GAME_LICENSE: u8 = 0;
static ADDON_LICENSES: u8 = 0;
fn offline(block: *mut AsyncBlock, what: &str) -> HRESULT {
tracing::info!(what, "store call: offline");
xasync::finished(block, (&raw const FAILED).cast(), NETWORK_ERROR)
}
extern "system" fn status(_: This, block: *mut AsyncBlock) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn create_context(_: This, _user: *const c_void, out: *mut Handle) -> HRESULT {
put(out, handle(&CONTEXT))
}
extern "system" fn close(_: This, _: Handle) {}
extern "system" fn associated_products_async(
_: This,
_: Handle,
_kinds: u32,
_per_page: u32,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "associated products")
}
extern "system" fn entitled_products_async(
_: This,
_: Handle,
_kinds: u32,
_per_page: u32,
block: *mut AsyncBlock,
) -> HRESULT {
xasync::finished_with(
block,
(&raw const QUERY_CALL).cast(),
Ok(xasync::bytes(handle(&QUERY))),
)
}
extern "system" fn query_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
xasync::result(block, (&raw const QUERY_CALL).cast(), out)
}
extern "system" fn enumerate_products(
_: This,
_: Handle,
_: *mut c_void,
_: *const c_void,
) -> HRESULT {
S_OK
}
extern "system" fn has_more_pages(_: This, _: Handle) -> bool {
false
}
extern "system" fn next_page_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
xasync::finished(block, (&raw const QUERY_CALL).cast(), E_ILLEGAL_METHOD_CALL)
}
fn license_for(owned: bool, block: *mut AsyncBlock) -> HRESULT {
let license = handle(if owned { &VALID } else { &INVALID });
xasync::finished_with(
block,
(&raw const LICENSE_CALL).cast(),
Ok(xasync::bytes(license)),
)
}
extern "system" fn license_for_package_async(
_: This,
_: Handle,
package: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
let ours = text(package).is_some_and(|p| p == xpackage::identifier());
license_for(ours, block)
}
extern "system" fn license_for_durables_async(
_: This,
_: Handle,
store_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::debug!(
store_id = text(store_id).unwrap_or_default(),
"durable not owned"
);
license_for(false, block)
}
extern "system" fn license_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
xasync::result(block, (&raw const LICENSE_CALL).cast(), out)
}
extern "system" fn is_license_valid(_: This, license: Handle) -> bool {
license == handle(&VALID)
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GameLicense {
pub sku_store_id: [u8; 18],
pub is_active: bool,
pub is_trial_owned_by_this_user: bool,
pub is_disc_license: bool,
pub is_trial: bool,
pub trial_seconds_remaining: u32,
pub trial_unique_id: [u8; 64],
pub expiration: i64,
}
fn game_license() -> GameLicense {
let mut sku = [0u8; 18];
let id = format!("{}/0010", runtime::title().store_id);
let len = id.len().min(sku.len() - 1);
sku[..len].copy_from_slice(&id.as_bytes()[..len]);
GameLicense {
sku_store_id: sku,
is_active: true,
is_trial_owned_by_this_user: false,
is_disc_license: false,
is_trial: false,
trial_seconds_remaining: 0,
trial_unique_id: [0; 64],
expiration: 0,
}
}
extern "system" fn game_license_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
let license = xasync::bytes(game_license());
xasync::finished_with(block, (&raw const GAME_LICENSE).cast(), Ok(license))
}
extern "system" fn game_license_result(
_: This,
block: *mut AsyncBlock,
out: *mut GameLicense,
) -> HRESULT {
xasync::result(block, (&raw const GAME_LICENSE).cast(), out)
}
#[allow(clippy::too_many_arguments)]
extern "system" fn products_async(
_: This,
_: Handle,
_kinds: u32,
_store_ids: *const *const c_char,
_store_id_count: usize,
_action_filters: *const *const c_char,
_action_filter_count: usize,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "products")
}
extern "system" fn product_for_game_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
offline(block, "product for the game")
}
extern "system" fn product_for_package_async(
_: This,
_: Handle,
_kinds: u32,
_package: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "product for a package")
}
extern "system" fn can_acquire_async(_: This, _: Handle, _id: *const c_char, block: *mut AsyncBlock) -> HRESULT {
offline(block, "licence acquisition check")
}
extern "system" fn struct_status(_: This, block: *mut AsyncBlock, _out: *mut c_void) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn addon_licenses_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
xasync::finished(block, (&raw const ADDON_LICENSES).cast(), S_OK)
}
extern "system" fn addon_license_count(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT {
match xasync::XAsyncGetStatus(block, false) {
S_OK => put(out, 0),
hr => hr,
}
}
extern "system" fn addon_licenses(_: This, block: *mut AsyncBlock, count: u32, _out: *mut c_void) -> HRESULT {
match xasync::XAsyncGetStatus(block, false) {
S_OK if count == 0 => S_OK,
S_OK => E_INVALIDARG,
hr => hr,
}
}
extern "system" fn consumable_balance_async(
_: This,
_: Handle,
_store_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "consumable balance")
}
extern "system" fn report_fulfillment_async(
_: This,
_: Handle,
_store_id: *const c_char,
_quantity: u32,
_tracking_id: *const c_void,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "consumable fulfillment")
}
extern "system" fn user_id_async(
_: This,
_: Handle,
_ticket: *const c_char,
_publisher_user_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "user store id")
}
extern "system" fn size_status(_: This, block: *mut AsyncBlock, _out: *mut usize) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn string_status(
_: This,
block: *mut AsyncBlock,
_: usize,
_: *mut c_char,
) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn count_status(_: This, block: *mut AsyncBlock, _out: *mut u32) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn array_status(
_: This,
block: *mut AsyncBlock,
_: u32,
_: *mut c_void,
) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn purchase_ui_async(
_: This,
_: Handle,
_store_id: *const c_char,
_name: *const c_char,
_json: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "purchase page")
}
extern "system" fn product_page_ui_async(
_: This,
_: Handle,
_store_id: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "product page")
}
extern "system" fn redeem_ui_async(
_: This,
_: Handle,
_token: *const c_char,
_allowed: *const *const c_char,
_allowed_count: usize,
_disallow_csv: bool,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "redeem page")
}
extern "system" fn updates_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
offline(block, "update check")
}
extern "system" fn install_async(
_: This,
_: Handle,
_ids: *const *const c_char,
_count: usize,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "package download")
}
extern "system" fn license_token_async(
_: This,
_: Handle,
_product_ids: *const *const c_char,
_count: usize,
_developer_string: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "licence token")
}
extern "system" fn rate_and_review_ui_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT {
offline(block, "rate and review page")
}
extern "system" fn associated_products_ui_async(
_: This,
_: Handle,
_store_id: *const c_char,
_kinds: u32,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "associated products page")
}
extern "system" fn gifting_ui_async(
_: This,
_: Handle,
_store_id: *const c_char,
_name: *const c_char,
_json: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "gifting page")
}
extern "system" fn associated_for_store_id_async(
_: This,
_: Handle,
_store_id: *const c_char,
_kinds: u32,
_per_page: u32,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "associated products for a store id")
}
extern "system" fn package_updates_async(
_: This,
_: Handle,
_ids: *const *const c_char,
_count: usize,
block: *mut AsyncBlock,
) -> HRESULT {
offline(block, "package update check")
}
extern "system" fn is_purchasable(_: This, _availability: *const c_void) -> bool {
false
}
extern "system" fn out_status(_: This, block: *mut AsyncBlock, _out: *mut c_void) -> HRESULT {
xasync::XAsyncGetStatus(block, false)
}
extern "system" fn package_identifier(
_: This,
store_id: *const c_char,
size: usize,
buffer: *mut u8,
) -> HRESULT {
let title = runtime::title();
match text(store_id) {
Some(id) if !title.store_id.is_empty() && id == title.store_id => {
put_string(&xpackage::identifier(), size, buffer, std::ptr::null_mut())
}
_ => E_INVALIDARG,
}
}
extern "system" fn register(
_: This,
_: Handle,
_queue: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
extern "system" fn unregister(_: This, _: Handle, _token: u64, _wait: bool) -> bool {
true
}
static VTABLE: Methods<92> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
create_context as *const (),
close as *const (),
associated_products_async as *const (),
query_result as *const (),
products_async as *const (),
query_result as *const (),
entitled_products_async as *const (),
query_result as *const (),
product_for_game_async as *const (),
query_result as *const (),
product_for_package_async as *const (),
query_result as *const (),
enumerate_products as *const (),
has_more_pages as *const (),
next_page_async as *const (),
query_result as *const (),
close as *const (),
license_for_package_async as *const (),
license_result as *const (),
is_license_valid as *const (),
close as *const (),
can_acquire_async as *const (),
struct_status as *const (),
can_acquire_async as *const (),
struct_status as *const (),
game_license_async as *const (),
game_license_result as *const (),
addon_licenses_async as *const (),
addon_license_count as *const (),
addon_licenses as *const (),
consumable_balance_async as *const (),
count_status as *const (),
report_fulfillment_async as *const (),
count_status as *const (),
user_id_async as *const (),
size_status as *const (),
string_status as *const (),
user_id_async as *const (),
size_status as *const (),
string_status as *const (),
license_token_async as *const (),
size_status as *const (),
string_status as *const (),
missing::<46> as *const (),
missing::<47> as *const (),
missing::<48> as *const (),
purchase_ui_async as *const (),
status as *const (),
rate_and_review_ui_async as *const (),
out_status as *const (),
redeem_ui_async as *const (),
status as *const (),
updates_async as *const (),
count_status as *const (),
array_status as *const (),
install_async as *const (),
status as *const (),
install_async as *const (),
status as *const (),
install_async as *const (),
count_status as *const (),
array_status as *const (),
package_identifier as *const (),
register as *const (),
unregister as *const (),
register as *const (),
unregister as *const (),
is_purchasable as *const (),
license_for_durables_async as *const (),
license_result as *const (),
associated_products_ui_async as *const (),
status as *const (),
product_page_ui_async as *const (),
status as *const (),
associated_for_store_id_async as *const (),
out_status as *const (),
package_updates_async as *const (),
count_status as *const (),
array_status as *const (),
gifting_ui_async as *const (),
status as *const (),
]);
+290
View File
@@ -0,0 +1,290 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::c_void;
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put_string, with_spare,
};
pub const PROVIDER: Guid = Guid::new(
0xe349_bd1a,
0xfc20,
0x4e40,
[0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f],
);
pub const IID: Guid = Guid::new(
0x6fd7_1f09,
0x7513,
0x49f0,
[0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52],
);
pub const ANALYTICS: Guid = Guid::new(
0xb884_675d,
0xb738,
0x4a9c,
[0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b],
);
const CONSOLE_ID: &str = "00000000000000000000000000000000000001";
const SANDBOX: &str = "RETAIL";
const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE=";
pub static OBJECT: Object = Object::new("system", &VTABLE);
pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE);
pub const IID_2026: Guid = Guid::new(
0x1861_cf2e,
0xe18b,
0x4834,
[0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf],
);
pub const INTERFACES: &[Interface] = &[
(PROVIDER, IID, &OBJECT),
(PROVIDER, IID_2026, &OBJECT),
(ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT),
];
type This = *const Object;
extern "system" fn console_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
put_string(CONSOLE_ID, size, buffer, used)
}
extern "system" fn sandbox_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
put_string(SANDBOX, size, buffer, used)
}
extern "system" fn device_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
put_string(DEVICE_ID, size, buffer, used)
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Version {
pub major: u16,
pub minor: u16,
pub build: u16,
pub revision: u16,
}
#[repr(C)]
pub struct AnalyticsInfo {
pub os: Version,
pub hosting_os: Version,
pub family: [u8; 64],
pub form: [u8; 64],
}
const OS: Version = Version {
major: 10,
minor: 0,
build: 22000,
revision: 0,
};
fn text(s: &str) -> [u8; 64] {
let mut out = [0; 64];
out[..s.len()].copy_from_slice(s.as_bytes());
out
}
extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut AnalyticsInfo {
let info = AnalyticsInfo {
os: OS,
hosting_os: OS,
family: text("Xbox"),
form: text(eonacat_xsbox_gpu::console::current().name()),
};
unsafe { out.write(info) };
out
}
extern "system" fn handle_track(_: This, _callback: *const (), _context: *mut c_void) -> HRESULT {
tracing::debug!("XSystemHandleTrack: runtime handles are not reported");
S_OK
}
extern "system" fn is_handle_valid(_: This, _handle: *const c_void) -> bool {
true
}
extern "system" fn allow_full_download_bandwidth(_: This, _enable: bool) {}
static VTABLE: Methods<17> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
console_id as *const (),
sandbox_id as *const (),
device_id as *const (),
handle_track as *const (),
is_handle_valid as *const (),
allow_full_download_bandwidth as *const (),
]);
static ANALYTICS_VTABLE: Methods<12> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
analytics_info as *const (),
]);
#[cfg(windows)]
mod device_type {
#![allow(non_snake_case)]
use std::ffi::c_void;
use eonacat_xsbox_gpu::console::{self, Console};
use crate::hle::modules::files::host;
use crate::hle::{HleModule};
use crate::hle_export;
type Key = *mut c_void;
const LOCAL_MACHINE: Key = 0xffff_ffff_8000_0002_u64 as Key;
const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\OEM";
const VALUE: &str = "ConsoleMode";
const SUCCESS: u32 = 0;
const FILE_NOT_FOUND: u32 = 2;
const INVALID_PARAMETER: u32 = 87;
const MORE_DATA: u32 = 234;
const DWORD: u32 = 4;
static OEM: u8 = 0;
fn oem() -> Key {
(&raw const OEM).cast_mut().cast()
}
pub(super) fn console_mode(console: Console) -> u32 {
match console {
Console::SeriesX => 0x64,
Console::SeriesS => 0x60,
}
}
fn is(text: *const u16, expected: &str) -> bool {
if text.is_null() {
return false;
}
let text = unsafe {
let len = (0..).take_while(|&i| *text.add(i) != 0).count();
String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
};
text.eq_ignore_ascii_case(expected)
}
fn open(root: Key, sub: *const u16, out: *mut Key) -> Option<u32> {
if root == oem() {
return Some(FILE_NOT_FOUND);
}
if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() {
unsafe { out.write(oem()) };
return Some(SUCCESS);
}
None
}
pub extern "system" fn RegOpenKeyW(root: Key, sub: *const u16, out: *mut Key) -> u32 {
open(root, sub, out).unwrap_or_else(|| {
host!("advapi32.dll", "RegOpenKeyW": extern "system" fn(Key, *const u16, *mut Key) -> u32)(
root, sub, out,
)
})
}
pub extern "system" fn RegOpenKeyExW(
root: Key,
sub: *const u16,
options: u32,
access: u32,
out: *mut Key,
) -> u32 {
open(root, sub, out).unwrap_or_else(|| {
host!("advapi32.dll", "RegOpenKeyExW": extern "system" fn(
Key, *const u16, u32, u32, *mut Key,
) -> u32)(root, sub, options, access, out)
})
}
pub extern "system" fn RegQueryValueExW(
key: Key,
name: *const u16,
reserved: *mut u32,
kind: *mut u32,
data: *mut u8,
size: *mut u32,
) -> u32 {
if key != oem() {
return host!("advapi32.dll", "RegQueryValueExW": extern "system" fn(
Key, *const u16, *mut u32, *mut u32, *mut u8, *mut u32,
) -> u32)(key, name, reserved, kind, data, size);
}
if !is(name, VALUE) {
return FILE_NOT_FOUND;
}
if !data.is_null() && size.is_null() {
return INVALID_PARAMETER;
}
unsafe {
if !kind.is_null() {
kind.write(DWORD);
}
if size.is_null() {
return SUCCESS;
}
let room = size.read();
size.write(4);
if data.is_null() {
return SUCCESS;
}
if room < 4 {
return MORE_DATA;
}
data.cast::<u32>()
.write_unaligned(console_mode(console::current()));
}
tracing::debug!(console = console::current().name(), "device type read");
SUCCESS
}
pub extern "system" fn RegCloseKey(key: Key) -> u32 {
if key == oem() {
return SUCCESS;
}
host!("advapi32.dll", "RegCloseKey": extern "system" fn(Key) -> u32)(key)
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "device type",
dlls: &[
"advapi32.dll",
"kernelbase.dll",
"api-ms-win-core-registry-*",
],
exports: vec![
hle_export!(RegOpenKeyW),
hle_export!(RegOpenKeyExW),
hle_export!(RegQueryValueExW),
hle_export!(RegCloseKey),
],
}
}
}
#[cfg(windows)]
pub(crate) use device_type::module;
+388
View File
@@ -0,0 +1,388 @@
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{c_char, c_void};
use super::xasync::{self, AsyncBlock, ProviderData};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text,
token, with_spare,
};
pub const PROVIDER: Guid = Guid {
data1: 0x01ac_d177,
data2: 0x91f9,
data3: 0x4763,
data4: [0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0],
};
pub const IID: Guid = Guid {
data1: 0xeb9b_f948,
data2: 0x18dc,
data3: 0x4d82,
data4: [0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0],
};
pub const GAMERTAG_IID: Guid = Guid {
data1: 0xcef4_fac0,
data2: 0x7676,
data3: 0x4a94,
data4: [0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74],
};
pub const DEVICE_PROVIDER: Guid = Guid::new(
0x7d82_4997,
0x10dc,
0x45ab,
[0x86, 0xb7, 0x27, 0x37, 0x76, 0x7c, 0x0b, 0xf1],
);
pub const DEVICE_IID: Guid = Guid::new(
0x0cc6_a956,
0xe7e1,
0x4fdf,
[0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8],
);
pub const USER_NOT_FOUND: HRESULT = 0x8924_5104_u32 as i32;
pub const XUID: u64 = 0x0009_0000_0000_0001;
pub const LOCAL_ID: u64 = 1;
const GAMERTAG: &str = "Player";
pub struct User;
static USER: User = User;
type Handle = *const User;
fn user() -> Handle {
&USER
}
fn found(found: bool, out: *mut Handle) -> HRESULT {
if found {
put(out, user())
} else {
USER_NOT_FOUND
}
}
pub static OBJECT: Object = Object::new("user", &VTABLE);
pub static GAMERTAG_OBJECT: Object = Object::new("user gamertag", &GAMERTAG_VTABLE);
pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE);
pub const INTERFACES: &[Interface] = &[
(PROVIDER, IID, &OBJECT),
(PROVIDER, PROVIDER, &OBJECT),
(PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT),
(DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT),
];
type This = *const Object;
extern "system" fn duplicate(_: This, _: Handle, out: *mut Handle) -> HRESULT {
put(out, user())
}
extern "system" fn close(_: This, _: Handle) {}
extern "system" fn compare(_: This, a: Handle, b: Handle) -> i32 {
i32::from(a != b)
}
extern "system" fn add_provider(op: u32, data: *const ProviderData) -> HRESULT {
const BEGIN: u32 = 0;
const GET_RESULT: u32 = 2;
let data = unsafe { &*data };
match op {
BEGIN => xasync::XAsyncComplete(data.block, S_OK, size_of::<Handle>()),
GET_RESULT => return put(data.buffer.cast::<Handle>(), user()),
_ => {}
}
S_OK
}
static ADD: u8 = 0;
extern "system" fn add_async(_: This, options: u32, block: *mut AsyncBlock) -> HRESULT {
tracing::info!(options, "XUserAddAsync: the offline local user");
xasync::XAsyncBegin(
block,
std::ptr::null_mut(),
(&raw const ADD).cast(),
std::ptr::null(),
Some(add_provider),
)
}
extern "system" fn add_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT {
xasync::XAsyncGetResult(
block,
(&raw const ADD).cast(),
size_of::<Handle>(),
out.cast(),
std::ptr::null_mut(),
)
}
extern "system" fn get_local_id(_: This, _: Handle, out: *mut u64) -> HRESULT {
put(out, LOCAL_ID)
}
extern "system" fn find_by_local_id(_: This, id: u64, out: *mut Handle) -> HRESULT {
found(id == LOCAL_ID, out)
}
extern "system" fn get_id(_: This, _: Handle, out: *mut u64) -> HRESULT {
put(out, XUID)
}
extern "system" fn find_by_id(_: This, id: u64, out: *mut Handle) -> HRESULT {
found(id == XUID, out)
}
extern "system" fn get_is_guest(_: This, _: Handle, out: *mut bool) -> HRESULT {
put(out, false)
}
extern "system" fn get_state(_: This, _: Handle, out: *mut u32) -> HRESULT {
put(out, 0)
}
extern "system" fn get_gamertag(
_: This,
_: Handle,
component: u32,
size: usize,
buffer: *mut u8,
used: *mut usize,
) -> HRESULT {
const MODERN_SUFFIX: u32 = 2;
let text = match component {
MODERN_SUFFIX => "",
_ => GAMERTAG,
};
put_string(text, size, buffer, used)
}
extern "system" fn check_privilege(
_: This,
_: Handle,
_options: u32,
_privilege: u32,
has: *mut bool,
reason: *mut u32,
) -> HRESULT {
if !reason.is_null() {
unsafe { reason.write(0) };
}
put(has, true)
}
extern "system" fn get_age_group(_: This, _: Handle, out: *mut u32) -> HRESULT {
put(out, 3)
}
static RESOLVE: u8 = 0;
static TOKEN: u8 = 0;
extern "system" fn resolve_privilege_async(
_: This,
_: Handle,
_options: u32,
_privilege: u32,
block: *mut AsyncBlock,
) -> HRESULT {
xasync::finished(block, (&raw const RESOLVE).cast(), S_OK)
}
extern "system" fn resolve_privilege_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const RESOLVE).cast(), 0, none, none.cast())
}
pub const FAILED_TO_GET_TOKEN: HRESULT = 0x8924_5111_u32 as i32;
#[allow(clippy::too_many_arguments)]
extern "system" fn token_async(
_: This,
_: Handle,
_options: u32,
_method: *const c_char,
url: *const c_char,
_header_count: usize,
_headers: *const c_void,
_body_size: usize,
_body: *const c_void,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::info!(
url = text(url).unwrap_or_default(),
"token and signature: offline"
);
xasync::finished(block, (&raw const TOKEN).cast(), FAILED_TO_GET_TOKEN)
}
extern "system" fn token_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
xasync::XAsyncGetResultSize(block, out)
}
extern "system" fn token_result(
_: This,
block: *mut AsyncBlock,
size: usize,
buffer: *mut c_void,
_data: *mut *const c_void,
used: *mut usize,
) -> HRESULT {
xasync::XAsyncGetResult(block, (&raw const TOKEN).cast(), size, buffer, used)
}
extern "system" fn max_users(_: This, out: *mut u32) -> HRESULT {
put(out, 1)
}
#[allow(clippy::too_many_arguments)]
extern "system" fn token_utf16_async(
_: This,
_: Handle,
_options: u32,
_method: *const u16,
_url: *const u16,
_header_count: usize,
_headers: *const c_void,
_body_size: usize,
_body: *const c_void,
block: *mut AsyncBlock,
) -> HRESULT {
tracing::info!("token and signature (UTF-16): offline");
xasync::finished(block, (&raw const TOKEN).cast(), FAILED_TO_GET_TOKEN)
}
extern "system" fn resolve_issue_async(
_: This,
_: Handle,
_url: *const c_void,
block: *mut AsyncBlock,
) -> HRESULT {
xasync::finished(block, (&raw const RESOLVE).cast(), S_OK)
}
const NO_PICTURE: HRESULT = 0x8000_4005_u32 as i32;
static PICTURE: u8 = 0;
extern "system" fn picture_async(
_: This,
_: Handle,
_size: u32,
block: *mut AsyncBlock,
) -> HRESULT {
xasync::finished(block, (&raw const PICTURE).cast(), NO_PICTURE)
}
extern "system" fn picture_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT {
xasync::XAsyncGetResultSize(block, out)
}
extern "system" fn picture_result(
_: This,
block: *mut AsyncBlock,
size: usize,
buffer: *mut c_void,
used: *mut usize,
) -> HRESULT {
xasync::XAsyncGetResult(block, (&raw const PICTURE).cast(), size, buffer, used)
}
pub const DEFERRAL_NOT_AVAILABLE: HRESULT = 0x8924_5103_u32 as i32;
extern "system" fn sign_out_deferral(_: This, out: *mut *const c_void) -> HRESULT {
if !out.is_null() {
unsafe { out.write(std::ptr::null()) };
}
DEFERRAL_NOT_AVAILABLE
}
extern "system" fn close_deferral(_: This, _deferral: *const c_void) {}
extern "system" fn add_by_id_async(this: This, id: u64, block: *mut AsyncBlock) -> HRESULT {
if id == XUID {
add_async(this, 0, block)
} else {
xasync::finished(block, (&raw const ADD).cast(), USER_NOT_FOUND)
}
}
extern "system" fn register(
_: This,
_queue: *const c_void,
_context: *mut c_void,
_callback: *const c_void,
out: *mut u64,
) -> HRESULT {
put(out, token())
}
extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool {
true
}
extern "system" fn find_for_device(_: This, device: *const [u8; 32], out: *mut Handle) -> HRESULT {
match unsafe { device.as_ref() } {
Some(id) => found(super::gameinput::is_device_id(id), out),
None => xasync::E_INVALIDARG,
}
}
static VTABLE: Methods<47> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
duplicate as *const (),
close as *const (),
compare as *const (),
max_users as *const (),
add_async as *const (),
add_result as *const (),
get_local_id as *const (),
find_by_local_id as *const (),
get_id as *const (),
find_by_id as *const (),
get_is_guest as *const (),
get_state as *const (),
get_gamertag as *const (),
picture_async as *const (),
picture_size as *const (),
picture_result as *const (),
get_age_group as *const (),
check_privilege as *const (),
resolve_privilege_async as *const (),
resolve_privilege_result as *const (),
token_async as *const (),
token_size as *const (),
token_result as *const (),
token_utf16_async as *const (),
token_size as *const (),
token_result as *const (),
resolve_issue_async as *const (),
resolve_privilege_result as *const (),
resolve_issue_async as *const (),
resolve_privilege_result as *const (),
register as *const (),
unregister as *const (),
sign_out_deferral as *const (),
close_deferral as *const (),
add_by_id_async as *const (),
add_result as *const (),
]);
static GAMERTAG_VTABLE: Methods<12> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
get_gamertag as *const (),
]);
static DEVICE_VTABLE: Methods<19> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
find_for_device as *const (),
register as *const (),
unregister as *const (),
missing::<6> as *const (),
register as *const (),
unregister as *const (),
missing::<9> as *const (),
missing::<10> as *const (),
]);
File diff suppressed because it is too large. Load diff
+61
View File
@@ -0,0 +1,61 @@
use std::sync::LazyLock;
use crate::hle::modules;
#[derive(Debug, Clone, Copy)]
pub struct HleExport {
pub name: &'static str,
pub address: usize,
}
#[derive(Debug)]
pub struct HleModule {
pub name: &'static str,
pub dlls: &'static [&'static str],
pub exports: Vec<HleExport>,
}
impl HleModule {
pub fn serves(&self, dll: &str) -> bool {
if !crate::hle::host::is_bare_dll_name(dll) {
return false;
}
let dll = dll.to_ascii_lowercase();
self.dlls
.iter()
.any(|pattern| match pattern.strip_suffix('*') {
Some(prefix) => dll.starts_with(prefix),
None => dll == *pattern,
})
}
}
#[macro_export]
macro_rules! hle_export {
($f:ident) => {
$crate::hle::HleExport {
name: stringify!($f),
address: $f as *const () as usize,
}
};
}
static REGISTRY: LazyLock<Vec<HleModule>> = LazyLock::new(modules::all);
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)
}
+320
View File
@@ -0,0 +1,320 @@
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread::ThreadId;
static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0);
pub fn set_main_image(base: usize) {
MAIN_IMAGE_BASE.store(base, Ordering::Release);
crate::hle::image_watch::start(base);
}
pub fn main_image() -> Option<usize> {
match MAIN_IMAGE_BASE.load(Ordering::Acquire) {
0 => None,
base => Some(base),
}
}
struct ImagePath {
base: usize,
path: PathBuf,
pending_on: Option<ThreadId>,
}
impl ImagePath {
fn visible_to(&self, thread: ThreadId) -> bool {
self.pending_on.is_none_or(|owner| owner == thread)
}
}
static IMAGE_PATHS: Mutex<Vec<ImagePath>> = Mutex::new(Vec::new());
fn insert_image_path(base: usize, path: &Path, pending_on: Option<ThreadId>) {
let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
paths.retain(|e| e.base != base);
paths.push(ImagePath {
base,
path,
pending_on,
});
}
pub fn set_image_path(base: usize, path: &Path) {
insert_image_path(base, path, None);
}
pub fn stage_image_path(base: usize, path: &Path) {
insert_image_path(base, path, Some(std::thread::current().id()));
}
pub fn publish_images(bases: &[usize]) {
if bases.is_empty() {
return;
}
let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
for entry in paths.iter_mut() {
if bases.contains(&entry.base) {
entry.pending_on = None;
}
}
}
pub fn forget_image(base: usize) {
let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
paths.retain(|e| e.base != base);
}
pub fn image_path(base: usize) -> Option<PathBuf> {
let me = std::thread::current().id();
let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
paths
.iter()
.find(|e| e.base == base && e.visible_to(me))
.map(|e| e.path.clone())
}
pub fn image_containing(address: usize) -> Option<usize> {
let me = std::thread::current().id();
let size = |base: usize| -> usize {
unsafe {
let nt = base + ((base + 0x3c) as *const u32).read_unaligned() as usize;
((nt + 0x50) as *const u32).read_unaligned() as usize
}
};
let bases: Vec<usize> = {
let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
paths
.iter()
.filter(|e| e.visible_to(me))
.map(|e| e.base)
.chain(main_image())
.collect()
};
bases
.into_iter()
.find(|&base| address >= base && address - base < size(base))
}
pub fn title_dir() -> Option<PathBuf> {
Some(image_path(main_image()?)?.parent()?.to_owned())
}
pub fn image_named(file: &str) -> Option<usize> {
let me = std::thread::current().id();
let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
paths
.iter()
.find(|e| {
e.visible_to(me)
&& e.path
.file_name()
.is_some_and(|n| n.eq_ignore_ascii_case(file))
})
.map(|e| e.base)
}
static TITLE_ARGS: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
pub fn set_title_args(args: Vec<String>) {
let _ = TITLE_ARGS.set(args);
}
pub fn title_args() -> &'static [String] {
TITLE_ARGS.get().map_or(&[], Vec::as_slice)
}
pub type TitleDllLoader = Box<dyn Fn(&str) -> Result<Option<usize>, String> + Send + Sync>;
static TITLE_DLL_LOADER: std::sync::OnceLock<TitleDllLoader> = std::sync::OnceLock::new();
pub fn set_title_dll_loader(loader: TitleDllLoader) {
let _ = TITLE_DLL_LOADER.set(loader);
}
pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> {
TITLE_DLL_LOADER.get().map_or(Ok(None), |load| load(file))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Title {
pub id: u32,
pub store_id: String,
pub storage: PathBuf,
pub storage_bytes: u64,
}
impl Title {
pub fn from_manifest(text: &str) -> Title {
let elements = elements(text);
let get = |path: &str| {
elements
.iter()
.find(|(p, _)| p == path)
.map(|(_, text)| text.as_str())
};
let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok());
let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse::<u64>().ok());
Title {
id: id.unwrap_or(0),
store_id: get("Game/StoreId").unwrap_or_default().to_owned(),
storage: PathBuf::new(),
storage_bytes: storage_mb.unwrap_or(0).saturating_mul(1 << 20),
}
}
pub fn saves(&self) -> PathBuf {
self.storage.with_file_name("saves")
}
pub fn screenshots(&self) -> PathBuf {
self.storage.with_file_name("screenshots")
}
}
fn field_text(rest: &str) -> String {
let mut out = String::new();
let mut rest = rest;
loop {
let Some(open) = rest.find('<') else {
out.push_str(rest);
break;
};
out.push_str(&rest[..open]);
if rest[open..].starts_with("<!--") {
let Some(end) = rest[open..].find("-->") else {
break;
};
rest = &rest[open + end + 3..];
} else {
break;
}
}
out.trim().to_owned()
}
fn elements(text: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut path: Vec<&str> = Vec::new();
let mut rest = text;
while let Some(open) = rest.find('<') {
rest = &rest[open..];
let end = if rest.starts_with("<!--") {
rest.find("-->").map(|e| e + 3)
} else if rest.starts_with("<![CDATA[") {
rest.find("]]>").map(|e| e + 3)
} else {
tag_end(rest)
};
let Some(end) = end else { break };
let tag = &rest[1..end - 1];
rest = &rest[end..];
if tag.starts_with(['!', '?']) {
continue;
}
if let Some(name) = tag.strip_prefix('/') {
if let Some(at) = path.iter().rposition(|n| *n == name.trim()) {
path.truncate(at);
}
continue;
}
let closed = tag.ends_with('/');
let name = tag
.trim_end_matches('/')
.split_whitespace()
.next()
.unwrap_or("");
path.push(name);
let body = field_text(rest);
let body = [("&lt;", "<"), ("&gt;", ">"), ("&quot;", "\""), ("&apos;", "'"), ("&amp;", "&")]
.iter()
.fold(body, |b, (entity, c)| b.replace(entity, c));
out.push((path.join("/"), body));
if closed {
path.pop();
}
}
out
}
fn tag_end(text: &str) -> Option<usize> {
let mut quote = None;
for (at, c) in text.char_indices() {
match (quote, c) {
(None, '"' | '\'') => quote = Some(c),
(Some(open), _) if c == open => quote = None,
(None, '>') => return Some(at + 1),
_ => {}
}
}
None
}
static TITLE: Mutex<Option<Title>> = Mutex::new(None);
pub fn set_title(title: Title) {
*TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title);
}
pub fn title() -> Title {
TITLE
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.unwrap_or_default()
}
#[cfg(windows)]
pub fn use_console_timers() {
use windows_sys::Win32::Media::timeBeginPeriod;
use windows_sys::Win32::System::Threading::{
GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, PROCESS_POWER_THROTTLING_EXECUTION_SPEED,
PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE,
ProcessPowerThrottling, SetProcessInformation,
};
let execution = if std::env::var_os("EONACAT_XS_EFFICIENCY_MODE").is_some_and(|v| v == "1") {
0
} else {
PROCESS_POWER_THROTTLING_EXECUTION_SPEED
};
let keep = PROCESS_POWER_THROTTLING_STATE {
Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION,
ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION | execution,
StateMask: 0,
};
unsafe {
SetProcessInformation(
GetCurrentProcess(),
ProcessPowerThrottling,
(&raw const keep).cast(),
size_of_val(&keep) as u32,
);
timeBeginPeriod(1);
}
ahead_of_other_programs();
eonacat_xsbox_gpu::place_process();
}
#[cfg(windows)]
fn ahead_of_other_programs() {
use windows_sys::Win32::System::Threading::{ABOVE_NORMAL_PRIORITY_CLASS, GetCurrentProcess, SetPriorityClass};
if std::env::var_os("EONACAT_XS_PROCESS_PRIORITY").is_some_and(|v| v == "normal" || v == "0") {
return;
}
let set = unsafe { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS) } != 0;
tracing::info!(set, "the process runs above normal priority (EONACAT_XS_PROCESS_PRIORITY=normal: not)");
}
+154
View File
@@ -0,0 +1,154 @@
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{Context, Result};
use eonacat_xsbox_gpu::pe::implib::ImportLibrary;
use eonacat_xsbox_gpu::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!("file size {} bytes", data.len());
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(", "))
}
}
+732
View File
@@ -0,0 +1,732 @@
mod cpu_budget;
mod hle;
mod census;
mod inspect;
#[cfg(windows)]
mod play;
#[cfg(all(windows, feature = "diagnostics"))]
mod replay;
mod run;
mod shader;
mod translate;
#[cfg(windows)]
mod warm;
use std::io::Write;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};
#[cfg(windows)]
#[unsafe(no_mangle)]
#[used]
#[allow(non_upper_case_globals)]
pub static D3D12SDKVersion: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(614);
fn agility_version(dll: &[u8]) -> Option<u32> {
let signature = 0xFEEF_04BD_u32.to_le_bytes();
let at = dll.windows(4).position(|w| w == signature)?;
let most = u32::from_le_bytes(dll.get(at + 8..at + 12)?.try_into().ok()?);
let (major, minor) = (most >> 16, most & 0xffff);
(major == 1 && minor >= 600).then_some(minor)
}
fn exported_sdk_version(dll: &[u8]) -> Option<u32> {
let u16_at = |at: usize| Some(u16::from_le_bytes(dll.get(at..at + 2)?.try_into().ok()?));
let u32_at = |at: usize| Some(u32::from_le_bytes(dll.get(at..at + 4)?.try_into().ok()?));
let pe = u32_at(0x3c)? as usize;
(dll.get(pe..pe + 4)? == b"PE\0\0").then_some(())?;
let sections = usize::from(u16_at(pe + 6)?);
let optional = pe + 24;
let table = optional + usize::from(u16_at(pe + 20)?);
(u16_at(optional)? == 0x20b).then_some(())?;
let offset = |rva: u32| -> Option<usize> {
(0..sections).find_map(|i| {
let s = table + i * 40;
let (size, va, raw_size, raw) = (u32_at(s + 8)?, u32_at(s + 12)?, u32_at(s + 16)?, u32_at(s + 20)?);
(va <= rva && rva < va + size.max(raw_size)).then(|| (rva - va + raw) as usize)
})
};
let exports = offset(u32_at(optional + 112)?)?;
let count = u32_at(exports + 24)? as usize;
let functions_at = offset(u32_at(exports + 28)?)?;
let names_at = offset(u32_at(exports + 32)?)?;
let ordinals_at = offset(u32_at(exports + 36)?)?;
(0..count).find_map(|i| {
let name = offset(u32_at(names_at + 4 * i)?)?;
if dll.get(name..name + 16)? != b"D3D12SDKVersion\0" {
return None;
}
let ordinal = usize::from(u16_at(ordinals_at + 2 * i)?);
u32_at(offset(u32_at(functions_at + 4 * ordinal)?)?)
})
}
#[cfg(windows)]
fn os_runtime() -> u32 {
let system = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into());
std::fs::read(system.join("System32").join("D3D12Core.dll"))
.ok()
.and_then(|dll| exported_sdk_version(&dll))
.map_or(4, |v| v.min(614))
}
#[cfg(windows)]
pub(crate) fn windows_build() -> Option<u32> {
if let Some(build) = std::env::var("EONACAT_XS_WINDOWS_BUILD").ok().and_then(|v| v.trim().parse().ok()) {
return Some(build);
}
#[repr(C)]
struct OsVersionInfo {
size: u32,
major: u32,
minor: u32,
build: u32,
platform: u32,
service_pack: [u16; 128],
}
#[link(name = "ntdll")]
unsafe extern "system" {
fn RtlGetVersion(info: *mut OsVersionInfo) -> i32;
}
let mut info = OsVersionInfo { size: size_of::<OsVersionInfo>() as u32, major: 0, minor: 0, build: 0, platform: 0, service_pack: [0; 128] };
(unsafe { RtlGetVersion(&mut info) } == 0).then_some(info.build)
}
#[cfg(windows)]
pub(crate) fn on_wine() -> bool {
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetModuleHandleW(name: *const u16) -> *mut core::ffi::c_void;
fn GetProcAddress(module: *mut core::ffi::c_void, name: *const core::ffi::c_char) -> *const core::ffi::c_void;
}
let ntdll: Vec<u16> = "ntdll.dll\0".encode_utf16().collect();
unsafe {
let module = GetModuleHandleW(ntdll.as_ptr());
!module.is_null() && !GetProcAddress(module, c"wine_get_version".as_ptr()).is_null()
}
}
#[cfg(windows)]
pub(crate) fn match_d3d12_core() {
use std::sync::atomic::Ordering::Relaxed;
let Some(core) = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.join("D3D12").join("D3D12Core.dll")))
else {
return;
};
let Ok(bytes) = std::fs::read(&core) else {
D3D12SDKVersion.store(os_runtime(), Relaxed);
return;
};
match agility_version(&bytes) {
Some(v) => {
if v != 614 {
println!("{} is the D3D12 Agility SDK 1.{v}: asking Windows for that version.", core.display());
}
D3D12SDKVersion.store(v, Relaxed);
}
None => {
D3D12SDKVersion.store(os_runtime(), Relaxed);
println!("{} is not a D3D12 Agility SDK runtime Windows can use: Windows' own is used.", core.display());
}
}
}
#[cfg(windows)]
#[repr(transparent)]
pub struct SdkPath(*const std::ffi::c_char);
#[cfg(windows)]
unsafe impl Sync for SdkPath {}
#[cfg(windows)]
#[unsafe(no_mangle)]
#[used]
#[allow(non_upper_case_globals)]
pub static D3D12SDKPath: SdkPath = SdkPath(c".\\D3D12\\".as_ptr());
#[cfg(windows)]
#[repr(C)]
pub struct DelayLoadInfo {
_size: u32,
_descriptor: *const std::ffi::c_void,
_function: *mut *const std::ffi::c_void,
dll: *const std::ffi::c_char,
}
#[cfg(windows)]
const DLI_NOTE_PRE_LOAD_LIBRARY: u32 = 1;
#[cfg(windows)]
static WINDOWS_COPY_BESIDE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[cfg(windows)]
fn is_d3d12(name: &[u8]) -> bool {
name.eq_ignore_ascii_case(b"d3d12.dll")
}
#[cfg(windows)]
fn loads_system32s(notify: u32, name: &[u8], windows_copy_beside: bool) -> bool {
windows_copy_beside && notify == DLI_NOTE_PRE_LOAD_LIBRARY && is_d3d12(name)
}
#[cfg(windows)]
fn windows_d3d12_version(dll: &[u8]) -> Option<[u32; 4]> {
let signature = 0xFEEF_04BD_u32.to_le_bytes();
let at = dll.windows(4).position(|w| w == signature)?;
let word = |o: usize| Some(u32::from_le_bytes(dll.get(at + o..at + o + 4)?.try_into().ok()?));
let (most, least) = (word(8)?, word(12)?);
let company: Vec<u8> = "Microsoft Corporation".encode_utf16().flat_map(u16::to_le_bytes).collect();
(most >> 16 == 10 && memchr::memmem::find(dll, &company).is_some())
.then_some([most >> 16, most & 0xffff, least >> 16, least & 0xffff])
}
#[cfg(windows)]
unsafe extern "system" fn delay_load_hook(notify: u32, info: *const DelayLoadInfo) -> *mut std::ffi::c_void {
if info.is_null() {
return std::ptr::null_mut();
}
let dll = unsafe { (*info).dll };
if dll.is_null() {
return std::ptr::null_mut();
}
let name = unsafe { std::ffi::CStr::from_ptr(dll) }.to_bytes();
let beside = WINDOWS_COPY_BESIDE.load(std::sync::atomic::Ordering::Relaxed);
if !loads_system32s(notify, name, beside) {
return std::ptr::null_mut();
}
system32_d3d12()
}
#[cfg(windows)]
fn system32_d3d12() -> *mut std::ffi::c_void {
#[link(name = "kernel32")]
unsafe extern "system" {
fn LoadLibraryExW(name: *const u16, file: *mut std::ffi::c_void, flags: u32) -> *mut std::ffi::c_void;
}
const LOAD_LIBRARY_SEARCH_SYSTEM32: u32 = 0x800;
let name: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect();
unsafe { LoadLibraryExW(name.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32) }
}
#[cfg(windows)]
#[unsafe(no_mangle)]
#[used]
#[allow(non_upper_case_globals)]
pub static __pfnDliNotifyHook2: Option<unsafe extern "system" fn(u32, *const DelayLoadInfo) -> *mut std::ffi::c_void> =
Some(delay_load_hook);
#[cfg(windows)]
fn check_d3d12_beside() {
let Some(beside) = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.join("d3d12.dll"))) else {
return;
};
let Some(v) = std::fs::read(&beside).ok().as_deref().and_then(windows_d3d12_version) else {
return;
};
WINDOWS_COPY_BESIDE.store(true, std::sync::atomic::Ordering::Relaxed);
println!(
"{} is a copy of Windows' own Direct3D 12 ({}.{}.{}.{}): not used, Windows' own from System32 is. \
Loaded from there, an older one held the shader model at 6.5, and even this PC's own failed; \
it can be deleted.",
beside.display(),
v[0],
v[1],
v[2],
v[3]
);
}
#[derive(Parser)]
#[command(
name = "eonacat-xsbox",
version,
about = "Run an Xbox Series title natively on Windows"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[allow(clippy::large_enum_variant)]
#[derive(Subcommand)]
enum Command {
Inspect {
file: PathBuf,
#[arg(long)]
imports: bool,
#[arg(long)]
exports: bool,
},
Census {
paths: Vec<PathBuf>,
#[arg(long)]
strict: bool,
#[arg(long)]
missing: bool,
},
LibExports {
lib: PathBuf,
#[arg(long)]
list: bool,
},
ShaderInfo {
paths: Vec<PathBuf>,
#[arg(long)]
verbose: bool,
#[arg(long)]
disasm: bool,
},
Translate {
paths: Vec<PathBuf>,
#[arg(long)]
validate: bool,
#[arg(long)]
pipelines: bool,
#[arg(long)]
list: bool,
#[arg(long)]
jobs: Option<NonZeroUsize>,
#[arg(long)]
warm: Option<PathBuf>,
},
Shaders {
paths: Vec<PathBuf>,
#[arg(long)]
jobs: Option<NonZeroUsize>,
},
#[cfg(windows)]
Warm {
#[arg(long)]
jobs: Option<usize>,
#[arg(long)]
limit: Option<usize>,
#[arg(long)]
again: bool,
#[arg(long)]
used: bool,
#[arg(long, hide = true)]
these: Option<String>,
},
#[cfg(windows)]
Preload {
paths: Vec<PathBuf>,
#[arg(long)]
jobs: Option<usize>,
#[arg(long, conflicts_with = "all")]
used: bool,
#[arg(long)]
all: bool,
},
#[cfg(windows)]
ClearShaders,
#[cfg(windows)]
Play(play::Play),
#[cfg(windows)]
GetDlss,
#[cfg(windows)]
GetFsr,
#[cfg(windows)]
GetD3d12,
#[cfg(windows)]
Pads {
#[arg(long, default_value_t = 60)]
seconds: u64,
},
#[cfg(windows)]
#[command(hide = true)]
ShaderModel,
#[cfg(windows)]
#[command(hide = true)]
HardwareRt,
Run {
exe: PathBuf,
#[arg(long, value_enum, default_value_t = Unimplemented::Trap)]
unimplemented: Unimplemented,
#[arg(long)]
strict: bool,
#[arg(long)]
execute: bool,
#[arg(long, value_enum, default_value_t = Console::SeriesX)]
console: Console,
#[arg(last = true)]
title_args: Vec<String>,
},
#[cfg(all(windows, feature = "diagnostics"))]
Replay(replay::Replay),
Config,
#[cfg(windows)]
UpscalerCheck {
#[arg(long, conflicts_with_all = ["present", "validate_framegen"])]
validate: bool,
#[arg(long, conflicts_with = "present")]
validate_framegen: bool,
#[arg(long, requires = "validate_framegen")]
combined: bool,
#[arg(long, requires = "validate_framegen")]
lifecycle: bool,
#[arg(long, default_value_t = 90, requires = "validate_framegen", value_parser = clap::value_parser!(u32).range(30..=18000))]
frames: u32,
#[arg(long, default_value_t = 20, requires = "validate_framegen", value_parser = clap::value_parser!(u32).range(0..=300))]
focus_wait: u32,
#[arg(long, default_value_t = 12, requires = "validate", value_parser = clap::value_parser!(u32).range(4..=48))]
iterations: u32,
#[arg(long, default_value = "2560x1440")]
output: String,
#[arg(long)]
device: bool,
#[arg(long)]
present: bool,
},
}
#[derive(Clone, Copy, ValueEnum)]
enum Unimplemented {
Trap,
Zero,
}
#[derive(Clone, Copy, ValueEnum)]
enum Console {
SeriesX,
SeriesS,
}
fn main() -> Result<()> {
crate::hle::memory_model::apply();
#[cfg(windows)]
match_d3d12_core();
#[cfg(windows)]
check_d3d12_beside();
#[cfg(windows)]
crate::hle::reserve_upload_space();
#[cfg(windows)]
crate::hle::modules::xmem::reserve_title_spare();
#[cfg(all(windows, feature = "diagnostics"))]
if std::env::var_os("EONACAT_XS_AUDIO_CAPTURE").is_some() {
eonacat_xsbox_gpu::core::logging::init("info");
if crate::hle::modules::audio::capture::child() {
return Ok(());
}
}
let bare = std::env::args_os().len() == 1;
let cli = if bare && cfg!(windows) { Cli::parse_from(["eonacat-xs", "play"]) } else { Cli::parse() };
#[cfg(windows)]
if let Command::Play(options) = &cli.command {
let preload = options.preload || std::env::var_os("EONACAT_XS_PRELOAD").is_some_and(|v| v == "1");
let clear = std::env::var_os("EONACAT_XS_CLEAR_SHADERS").is_some_and(|v| v == "1");
let named_cache = std::env::var_os("EONACAT_XS_CACHE_DIR").is_some();
let done = play::prepare(options).and_then(|ready| {
play::clear_stale_shaders(named_cache);
if clear && let Err(e) = play::clear_shaders() {
println!("The shader cache was not cleared: {e:#}. Starting the game.");
}
let mark = play::preload_needed(&ready);
if preload || mark.is_some() {
play::preload(&ready.exe, mark.as_deref());
}
eonacat_xsbox_gpu::core::logging::init("info");
crate::hle::memory_model::say();
play::load_mods();
let console = if ready.series_s { Console::SeriesS } else { Console::SeriesX };
#[cfg(windows)]
crate::hle::console_window::hide();
run::run(&ready.exe, Unimplemented::Trap, false, true, console)
});
if let Err(e) = &done
&& bare
{
eprintln!("Error: {e:#}");
play::hold_window();
}
return done;
}
#[cfg(windows)]
if matches!(cli.command, Command::Shaders { .. } | Command::Warm { .. } | Command::Preload { .. }) {
let named_cache = std::env::var_os("EONACAT_XS_CACHE_DIR").is_some();
play::apply_defaults();
if !matches!(cli.command, Command::Warm { these: Some(_), .. }) {
play::clear_stale_shaders(named_cache);
}
}
eonacat_xsbox_gpu::core::logging::init("info");
crate::hle::memory_model::say();
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::Translate {
paths,
validate,
pipelines,
list,
jobs,
warm,
} => {
if let Some(n) = std::env::var("EONACAT_XS_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) {
eonacat_xsbox_gpu::shader::emit::set_view_heap_limit(n);
}
if let Some(n) = std::env::var("EONACAT_XS_HOST_WAVE").ok().and_then(|v| v.parse().ok()) {
eonacat_xsbox_gpu::shader::emit::set_host_max_wave(n);
}
let jobs = jobs.map(NonZeroUsize::get);
if let Some(file) = warm {
return translate::warm(paths, &file, jobs);
}
translate::run(paths, validate, pipelines, list, jobs)
}
Command::Shaders { paths, jobs } => {
translate::precompile(paths, jobs.map(NonZeroUsize::get))
}
#[cfg(windows)]
Command::Warm { jobs, limit, again, used, these } => warm::run(jobs, limit, again, used, these),
#[cfg(windows)]
Command::Preload { paths, jobs, used, all } => {
let jobs = jobs
.or_else(|| std::env::var("EONACAT_XS_PRELOAD_JOBS").ok()?.trim().parse().ok())
.filter(|&n| n > 0);
if let Some(n) = jobs {
println!("Preloading on {n} threads at a time (EONACAT_XS_PRELOAD_JOBS / --jobs).");
}
play::explain_preload();
println!("EONACAT_PRELOAD|SHADERS");
let _ = std::io::stdout().flush();
translate::precompile(paths, jobs)?;
let recorded = warm::used_pipelines_recorded()?;
let used = preload_used(used, all, recorded);
println!(
"Pipeline warm-up: {}",
if used {
"only pipelines used by earlier runs (--all warms every known pipeline)"
} else if recorded {
"every known pipeline (--all)"
} else {
"every known pipeline (no earlier run left a list of enough pipelines; --used skips the full warm-up)"
}
);
println!("EONACAT_PRELOAD|PIPELINES");
let _ = std::io::stdout().flush();
warm::run(jobs, None, false, used, None)?;
warm::into_library(jobs)
}
#[cfg(windows)]
Command::ClearShaders => play::clear_shaders(),
#[cfg(windows)]
Command::Play(_) => unreachable!("handled above"),
#[cfg(windows)]
Command::GetDlss => play::get_dlss(),
#[cfg(windows)]
Command::GetFsr => play::get_fsr(),
#[cfg(windows)]
Command::GetD3d12 => play::get_d3d12(),
#[cfg(windows)]
Command::Pads { seconds } => {
play::pad_settings();
crate::hle::modules::gameinput::monitor_pads(seconds);
Ok(())
}
#[cfg(windows)]
Command::ShaderModel => {
if let Some(card) = crate::hle::streamline::adapter_name() {
println!("card {card}");
}
let model = crate::hle::streamline::highest_shader_model();
if let Some(core) = crate::hle::streamline::d3d12_core_path() {
println!("runtime {}", core.display());
}
match model {
Some((major, minor)) => println!("{major}.{minor}"),
None => println!("none"),
}
Ok(())
}
#[cfg(windows)]
Command::HardwareRt => {
match crate::hle::streamline::card_hardware_rt() {
Some(true) => println!("dxr 1.1"),
Some(false) => println!("no dxr 1.1"),
None => println!("no device"),
}
Ok(())
}
Command::Run {
exe,
unimplemented,
strict,
execute,
console,
title_args,
} => {
crate::hle::runtime::set_title_args(title_args);
play::load_mods();
#[cfg(windows)]
if execute {
crate::hle::console_window::hide();
}
run::run(&exe, unimplemented, strict, execute, console)
}
#[cfg(all(windows, feature = "diagnostics"))]
Command::Replay(options) => replay::run(options),
Command::Config => show_config(),
#[cfg(windows)]
Command::UpscalerCheck { output, device, present, validate, iterations, validate_framegen, lifecycle, frames, focus_wait, combined } => {
let size = output
.split_once(['x', 'X'])
.and_then(|(w, h)| Some([w.trim().parse().ok()?, h.trim().parse().ok()?]))
.ok_or_else(|| anyhow::anyhow!("--output {output}: not <width>x<height>"))?;
let lines = if combined {
crate::hle::streamline::combined_check(size, frames, lifecycle, focus_wait).map_err(anyhow::Error::msg)?
} else if validate_framegen {
crate::hle::streamline::framegen_check(size, frames, lifecycle, focus_wait).map_err(anyhow::Error::msg)?
} else if validate {
crate::hle::streamline::verified_check(size, iterations).map_err(anyhow::Error::msg)?
} else {
crate::hle::streamline::check(size, device || present, present)
};
for line in lines {
println!("{line}");
}
Ok(())
}
}
}
fn show_config() -> Result<()> {
let cfg = eonacat_xsbox_gpu::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());
println!("data_dir : {}", cfg.data_dir.display());
Ok(())
}
#[cfg(windows)]
fn preload_used(requested: bool, all: bool, recorded: bool) -> bool {
!all && (requested || recorded)
}
pub(crate) fn default_paths(paths: Vec<PathBuf>) -> Result<Vec<PathBuf>> {
if !paths.is_empty() {
return Ok(paths);
}
let cfg = eonacat_xsbox_gpu::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"
);
Ok(all)
}
+242
View File
@@ -0,0 +1,242 @@
use anyhow::{Context, Result, ensure};
use eonacat_xsbox_gpu::formats::texture::{Dimension, Swizzle, Texture, TextureDesc};
use crate::hle::streamline::Mode;
use eonacat_xsbox_gpu::loader::PreparedImage;
pub(super) fn same(bytes: &[u8], hash: &str) -> bool {
blake3::hash(bytes).to_hex().as_str() == hash
}
pub(super) const RETAIL_BUILD: &str = "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93";
const ALLOW_MODDED_ENV: &str = "EONACAT_XS_ALLOW_MODDED";
fn allow_modded() -> bool {
std::env::var(ALLOW_MODDED_ENV).as_deref() == Ok("1")
}
pub(super) fn size() -> (u32, u32) {
static SIZE: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new();
*SIZE.get_or_init(|| {
let asked = std::env::var("EONACAT_XS_NATIVE_SIZE").ok().and_then(|v| {
let (w, h) = v.trim().split_once(['x', 'X'])?;
Some((w.trim().parse::<u32>().ok()?, h.trim().parse::<u32>().ok()?))
});
match asked {
Some(size) if usable(size) => size,
_ if std::env::var("EONACAT_XS_NATIVE_WIDE").as_deref() == Ok("1") => {
monitor_size().map_or(DEFAULT, for_monitor)
}
_ => DEFAULT,
}
})
}
const DEFAULT: (u32, u32) = (2560, 1440);
fn usable((w, h): (u32, u32)) -> bool {
(1280..=7680).contains(&w) && (720..=4320).contains(&h) && w % 8 == 0 && h % 8 == 0
}
fn for_monitor((w, h): (u32, u32)) -> (u32, u32) {
if w == 0 || h == 0 {
return DEFAULT;
}
if (u64::from(w) * 9).abs_diff(u64::from(h) * 16) * 100 <= u64::from(h) * 16 {
return DEFAULT;
}
if h < DEFAULT.1 || u64::from(w) * 9 < u64::from(h) * 16 {
return DEFAULT;
}
let height = h.min(DEFAULT.1) / 8 * 8;
let width = (u64::from(height) * u64::from(w) / u64::from(h)) as u32 / 8 * 8;
let size = (width.min(7680), height);
if usable(size) { size } else { DEFAULT }
}
#[cfg(windows)]
fn monitor_size() -> Option<(u32, u32)> {
use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_CXSCREEN, SM_CYSCREEN};
let (w, h) = unsafe { (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)) };
Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?))
}
#[cfg(not(windows))]
fn monitor_size() -> Option<(u32, u32)> {
None
}
pub(super) fn width() -> u32 {
size().0
}
pub(super) fn height() -> u32 {
size().1
}
const SDR_MODE: u32 = 0x0615_c100;
const STOCK_SDR_MODE: &str = "abfb5438d8153b6a0b8d08f33f4f0066e5383925b55aacc5f669131f3f51d4cf";
const LEGACY_UI_WIDTH: u32 = 3840;
const LEGACY_UI_HEIGHT: u32 = 2160;
const UI_POOL: u32 = 0x0247_ad4a;
const TEMPORAL_SCALE: u32 = 0x028f_1e7e;
const SETTINGS_COPY: u32 = 0x01d7_0b98;
const STOCK_SETTINGS_COPY: &str = "9d8829e6720f7624fd7004b8905ccfd6e1d9c6610ec186100f8350e091344038";
const SETTINGS_COPY_LEN: usize = 11;
const SETTINGS_CAVE: u32 = 0x055f_f285;
const SETTINGS_CAVE_LEN: usize = 59;
fn settings_cave_bytes() -> Result<Vec<u8>> {
let pair = |w: u32, h: u32| (u64::from(h) << 32 | u64::from(w)).to_le_bytes();
let mut cave = Vec::with_capacity(SETTINGS_CAVE_LEN);
cave.extend_from_slice(&[0xc5, 0xfe, 0x7f, 0x86, 0x38, 0x06, 0, 0]);
cave.extend_from_slice(&[0xc6, 0x86, 0x38, 0x06, 0, 0, 0x01]);
cave.extend_from_slice(&[0x48, 0xb8]);
cave.extend_from_slice(&pair(LEGACY_UI_WIDTH, LEGACY_UI_HEIGHT));
cave.extend_from_slice(&[0x48, 0x89, 0x86, 0x3c, 0x06, 0, 0]);
cave.extend_from_slice(&[0x48, 0xb8]);
cave.extend_from_slice(&pair(width(), height()));
cave.extend_from_slice(&[0x48, 0x89, 0x86, 0x54, 0x06, 0, 0]);
cave.extend_from_slice(&[0xc5, 0xf8, 0x77]);
let back = i64::from(SETTINGS_COPY) + SETTINGS_COPY_LEN as i64 - (i64::from(SETTINGS_CAVE) + cave.len() as i64 + 5);
cave.push(0xe9);
cave.extend_from_slice(&i32::try_from(back)?.to_le_bytes());
ensure!(cave.len() <= SETTINGS_CAVE_LEN, "settings cave code too long");
Ok(cave)
}
fn settings_copy_bytes() -> Result<[u8; SETTINGS_COPY_LEN]> {
let mut site = [0x90; SETTINGS_COPY_LEN];
site[0] = 0xe9;
let to = i64::from(SETTINGS_CAVE) - (i64::from(SETTINGS_COPY) + 5);
site[1..5].copy_from_slice(&i32::try_from(to)?.to_le_bytes());
Ok(site)
}
fn ui_surface_bytes(width: u32, height: u32) -> Result<u64> {
let texture = Texture::new(&TextureDesc {
dimension: Dimension::Tex2d,
width,
height,
depth_or_array: 1,
mips: 1,
format: 28,
samples: 1,
swizzle: Swizzle::SW_64KB_D_X,
})
.map_err(|error| anyhow::anyhow!("UI surface layout ({width}x{height}): {error:?}"))?;
Ok(texture.size.next_multiple_of(64 * 1024))
}
pub(super) fn prepare(image: &mut PreparedImage, render_1080p: bool) -> Result<(u32, u32)> {
ensure!(
allow_modded() || image.original_hash.to_hex().as_str() == RETAIL_BUILD,
"1440p output is only known for the retail build {RETAIL_BUILD} (set {ALLOW_MODDED_ENV}=1 to allow a modded copy)"
);
ensure!(same(&field::<16>(image, SDR_MODE)?[..], STOCK_SDR_MODE), "unexpected Series X SDR mode");
let pool_size = u32::try_from(
(ui_surface_bytes(LEGACY_UI_WIDTH, LEGACY_UI_HEIGHT)? * 2 + ui_surface_bytes(DEFAULT.0, DEFAULT.1)? * 2)
.next_multiple_of(2 << 20),
)?;
let pool = field::<5>(image, UI_POOL)?;
ensure!(*pool == [0xb9, 0, 0, 0, 4], "unexpected Series X UI pool size");
pool[1..].copy_from_slice(&pool_size.to_le_bytes());
let site = field::<SETTINGS_COPY_LEN>(image, SETTINGS_COPY)?;
ensure!(same(&site[..], STOCK_SETTINGS_COPY), "unexpected settings copy");
let cave = field::<SETTINGS_CAVE_LEN>(image, SETTINGS_CAVE)?;
ensure!(cave.iter().all(|b| *b == 0xcc), "settings cave is not free padding");
let code = settings_cave_bytes()?;
cave[..code.len()].copy_from_slice(&code);
*field::<SETTINGS_COPY_LEN>(image, SETTINGS_COPY)? = settings_copy_bytes()?;
let scale = field::<4>(image, TEMPORAL_SCALE)?;
ensure!(*scale == (2.0f32 / 3.0).to_le_bytes(), "unexpected Series X temporal scene scale");
let (render_width, render_height) = if render_1080p { (1920, 1080) } else { (width(), height()) };
*scale = (render_width as f32 / width() as f32).to_le_bytes();
Ok((render_width, render_height))
}
const RENDERER_SELECTION: u32 = 0x007e_9421;
const STOCK_RENDERER_SELECTION: &str = "f0633abf37df17124108b1e37be64645bd4b2412b0524c2f89334f22bd948464";
const UPSCALER_SIZING: u32 = 0x028e_f69a;
const STOCK_UPSCALER_SIZING: &str = "2ae2ac102d12ca003cb218413ef018e4dba68fc2003654a30c1743e13a820ffd";
const NATIVE_LOAD: u32 = 0x028e_f6a8;
const STOCK_NATIVE_LOAD: &str = "2579c24601d173b086a8136edf54ffd82720e6bf186f9139274bb09a45ddadf5";
const SCALED_LOAD: u32 = 0x028e_f6b2;
const STOCK_SCALED_LOAD: &str = "e218882c95d2e16163a409d55b3451519414eb87c4d6220785dc09852d4e14f4";
const UPSCALER_SCALE: u32 = 0x0615_d95c;
pub(super) fn prepare_temporal(image: &mut PreparedImage) -> Result<()> {
ensure!(
image.original_hash.to_hex().as_str() == RETAIL_BUILD,
"the renderer selection is only known for the retail build {RETAIL_BUILD}"
);
ensure!(same(&field::<8>(image, RENDERER_SELECTION)?[..], STOCK_RENDERER_SELECTION), "unexpected renderer selection");
*field::<8>(image, RENDERER_SELECTION)? = [0xb8, 6, 0, 0, 0, 0x90, 0x90, 0x90];
Ok(())
}
pub(super) fn prepare_upscaler(image: &mut PreparedImage, mode: Mode) -> Result<()> {
ensure!(
allow_modded() || image.original_hash.to_hex().as_str() == RETAIL_BUILD,
"the upscaler path is only known for the retail build {RETAIL_BUILD} (set {ALLOW_MODDED_ENV}=1 to allow a modded copy)"
);
ensure!(same(&field::<8>(image, RENDERER_SELECTION)?[..], STOCK_RENDERER_SELECTION), "unexpected renderer selection");
ensure!(same(&field::<14>(image, UPSCALER_SIZING)?[..], STOCK_UPSCALER_SIZING), "unexpected upscaler render size selection");
ensure!(same(&field::<10>(image, NATIVE_LOAD)?[..], STOCK_NATIVE_LOAD), "unexpected upscaler native scale load");
ensure!(same(&field::<8>(image, SCALED_LOAD)?[..], STOCK_SCALED_LOAD), "unexpected upscaler scaled load");
ensure!(*field::<4>(image, UPSCALER_SCALE)? == (2.0f32 / 3.0).to_le_bytes(), "unexpected upscaler scale");
let temporal = f32::from_le_bytes(*field::<4>(image, TEMPORAL_SCALE)?);
ensure!(
temporal == 2.0 / 3.0 || temporal == 1.0,
"unexpected temporal scene scale {temporal} (stock 2/3, or 1 with the 1440p output)"
);
*field::<8>(image, RENDERER_SELECTION)? = [0xb8, 7, 0, 0, 0, 0x90, 0x90, 0x90];
*field::<14>(image, UPSCALER_SIZING)? = [0xb8, mode.ffx_mode(), 0, 0, 0, 0x41, 0x89, 0x86, 0x90, 0, 0, 0, 0xeb, 0x0a];
if mode != Mode::Quality {
let literal = NATIVE_LOAD + 4;
*field::<4>(image, literal)? = mode.scale().to_le_bytes();
let displacement = literal as i32 - (SCALED_LOAD as i32 + 8);
*field::<4>(image, SCALED_LOAD + 4)? = displacement.to_le_bytes();
}
*field::<4>(image, TEMPORAL_SCALE)? = mode.scale().to_le_bytes();
Ok(())
}
pub(super) fn prepare_native_scene(image: &mut PreparedImage) -> Result<()> {
ensure!(
image.original_hash.to_hex().as_str() == RETAIL_BUILD,
"the full-size scene is only known for the retail build {RETAIL_BUILD}"
);
let scale = field::<4>(image, TEMPORAL_SCALE)?;
ensure!(*scale == (2.0f32 / 3.0).to_le_bytes(), "unexpected Series X temporal scene scale");
*scale = 1.0f32.to_le_bytes();
Ok(())
}
fn field<const N: usize>(image: &mut PreparedImage, rva: u32) -> Result<&mut [u8; N]> {
let offset = image.info.rva_to_file_offset(rva).context("display profile field missing")? as usize;
image
.bytes
.get_mut(offset..offset + N)
.context("incomplete display profile field")?
.try_into()
.context("invalid display profile field length")
}
File diff suppressed because it is too large. Load diff
+466
View File
@@ -0,0 +1,466 @@
use std::path::PathBuf;
use anyhow::{Context, Result};
use clap::{Args, ValueEnum};
use crate::hle::replay::play::{self, Options};
#[derive(Clone, Copy, ValueEnum)]
enum Timing {
Lists,
Detailed,
}
#[derive(Clone, Copy, ValueEnum)]
enum Buffers {
AsRecorded,
Vram,
Sysmem,
}
#[derive(Args)]
pub(crate) struct Replay {
folder: PathBuf,
#[arg(long, default_value_t = 5)]
loops: u32,
#[arg(long)]
no_restore: bool,
#[arg(long, value_enum, default_value_t = Timing::Lists)]
timing: Timing,
#[arg(long, default_value_t = 20)]
top: usize,
#[arg(long)]
image: Option<PathBuf>,
#[arg(long)]
compare: bool,
#[arg(long)]
no_barriers: bool,
#[arg(long)]
merge_barriers: bool,
#[arg(long)]
skip_clamps: bool,
#[arg(long, num_args = 0..=1, default_missing_value = "1", default_value_t = 0)]
batch_clamps: u32,
#[arg(long)]
skip_hash_passes: bool,
#[arg(long, value_enum, default_value_t = Buffers::AsRecorded)]
buffers: Buffers,
#[arg(long)]
only_buffers: Vec<String>,
#[arg(long)]
one_submit: bool,
#[arg(long)]
no_merge: bool,
#[arg(long)]
wait_all: bool,
#[arg(long)]
wait_lists: bool,
#[arg(long, default_value_t = 0.0)]
pace: f64,
#[arg(long)]
awake: bool,
#[arg(long)]
breadcrumbs: bool,
#[arg(long)]
only: Option<String>,
#[arg(long = "skip-shader")]
skip_shader: Vec<String>,
#[arg(long, num_args = 0..=1, default_missing_value = "3")]
diverge: Option<u32>,
#[arg(long, num_args = 0..=1, default_missing_value = "5")]
diverge_picture: Option<u32>,
#[arg(long)]
draws: Option<String>,
#[arg(long)]
watch: Vec<String>,
#[arg(long)]
commands: Option<String>,
#[arg(long, default_value_t = 1)]
step: usize,
#[arg(long)]
lists: Option<String>,
#[arg(long, default_value_t = 4)]
roots: u32,
#[arg(long)]
check_written: bool,
#[arg(long)]
upcopies: bool,
#[arg(long)]
slots: Option<String>,
#[arg(long)]
dump: Option<String>,
#[arg(long)]
listing: Option<String>,
#[arg(long)]
flow: Option<String>,
#[arg(long)]
flow_draws: bool,
#[arg(long, default_value_t = 40)]
flow_slots: u32,
#[arg(long)]
images: Option<PathBuf>,
#[arg(long)]
texture: Vec<String>,
#[arg(long, default_value_t = 4096)]
least: u64,
#[arg(long, default_value_t = 960)]
width: u32,
#[arg(long)]
raw: bool,
#[arg(long)]
until: Option<String>,
#[arg(long)]
pixel: Vec<String>,
#[arg(long)]
of: Option<String>,
#[arg(long)]
depth: bool,
#[arg(long)]
targets_only: bool,
#[arg(long)]
split: Vec<String>,
#[arg(long)]
shaders: Option<PathBuf>,
#[arg(long)]
shaders_b: Option<PathBuf>,
#[arg(long)]
retranslate: Option<PathBuf>,
#[arg(long, default_value_t = 0)]
view_limit: u32,
#[arg(long, default_value_t = 0)]
raw_views: u32,
#[arg(long)]
debug_layer: bool,
}
fn range(text: &str) -> Option<(u32, u32)> {
match text.split_once("..") {
Some((a, b)) => Some((a.trim().parse().ok()?, b.trim().parse().ok()?)),
None => text.trim().parse().ok().map(|n| (n, n)),
}
}
fn pair(text: &str, by: char) -> Option<(u32, u32)> {
let (a, b) = text.split_once(by)?;
Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
}
pub(crate) fn run(r: Replay) -> Result<()> {
if let Some(text) = &r.dump {
for line in play::dump(&r.folder, text)? {
println!("{line}");
}
return Ok(());
}
if let Some(text) = &r.listing {
let lists = range(text).with_context(|| format!("--listing {text}"))?;
return play::listing(&r.folder, lists, &mut |line| println!("{line}"));
}
if let Some(text) = &r.flow {
let lists = range(text).with_context(|| format!("--flow {text}"))?;
return play::look::flow(&r.folder, lists, r.flow_draws, r.flow_slots, &mut |line| println!("{line}"));
}
if let Some(into) = &r.retranslate {
return retranslate(&r.folder, into, r.view_limit, r.raw_views);
}
let until = match &r.until {
Some(text) => Some(
text.split_once(':')
.and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?)))
.with_context(|| format!("--until {text}: not <list>:<command>"))?,
),
None => None,
};
let only = match &r.only {
Some(text) => Some(
range(text)
.with_context(|| format!("--only {text}: not a list or a range of lists (3..7)"))?,
),
None => None,
};
let options = Options {
loops: r.loops.max(1),
restore: !r.no_restore,
detailed: matches!(r.timing, Timing::Detailed),
top: r.top,
image: r.image,
buffers: match r.buffers {
Buffers::AsRecorded => play::Buffers::AsRecorded,
Buffers::Vram => play::Buffers::Card,
Buffers::Sysmem => play::Buffers::Pc,
},
only_buffers: r.only_buffers,
no_barriers: r.no_barriers,
merge_barriers: r.merge_barriers,
skip_clamps: r.skip_clamps,
batch_clamps: r.batch_clamps,
skip_hash_passes: r.skip_hash_passes,
one_submit: r.one_submit,
merge: !r.no_merge,
wait_all: r.wait_all,
wait_lists: r.wait_lists,
pace: r.pace,
awake: r.awake,
only,
until,
skip_shaders: r.skip_shader,
shaders: r.shaders,
shaders_b: r.shaders_b,
compare: r.compare,
debug: r.debug_layer,
breadcrumbs: r.breadcrumbs,
};
if let Some(text) = &r.slots {
let (list, command) = text
.split_once(':')
.and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?)))
.with_context(|| format!("--slots {text}: not <list>:<command>"))?;
let player = play::Player::load(&r.folder, &options)?;
return player.slots(list, command, &mut |line| println!("{line}"));
}
if let Some(folder) = &r.images {
let mut which = Vec::new();
for text in &r.texture {
let (id, sub) = text.split_once('.').unwrap_or((text, "0"));
let bad = || format!("--texture {text}");
which.push((id.parse().with_context(bad)?, sub.parse().with_context(bad)?));
}
let images = play::look::Images {
which,
least: r.least,
folder: folder.clone(),
width: r.width,
raw: r.raw,
};
let mut player = play::Player::load(&r.folder, &options)?;
return player.images(&options, &images, &mut |line| println!("{line}"));
}
if !r.pixel.is_empty() {
let mut player = play::Player::load(&r.folder, &options)?;
let mut pixels = play::pixel::Pixels {
depth: r.depth,
written: !r.targets_only,
..Default::default()
};
if let Some(text) = &r.lists {
pixels.lists = Some(range(text).with_context(|| format!("--lists {text}"))?);
}
let of = match &r.of {
Some(text) => Some(pair(text, 'x').with_context(|| format!("--of {text}"))?),
None => None,
};
for text in &r.pixel {
let bad = || format!("--pixel {text}");
match text.split_once(':') {
Some((what, at)) => {
let (id, sub) = what.split_once('.').unwrap_or((what, "0"));
let (x, y) = pair(at, ',').with_context(bad)?;
let id = id.parse().with_context(bad)?;
let sub = sub.parse().with_context(bad)?;
pixels.texels.push((id, sub, x, y));
}
None => {
let (mut x, mut y) = pair(text, ',').with_context(bad)?;
if let (Some((w, h)), Some((pw, ph))) = (of, player.picture_size()) {
x = x * pw / w.max(1);
y = y * ph / h.max(1);
}
pixels.points.push((x, y));
}
}
}
for text in &r.split {
pixels
.split
.push(pair(text, ':').with_context(|| format!("--split {text}"))?);
}
return player.pixel(&options, &pixels, &mut |line| println!("{line}"));
}
if r.check_written {
let mut player = play::Player::load(&r.folder, &options)?;
return player.check_written(&mut |line| println!("{line}"));
}
if r.upcopies {
let mut player = play::Player::load(&r.folder, &options)?;
return player.upcopies(&options, &mut |line| println!("{line}"));
}
let mut watched = Vec::new();
for text in &r.watch {
let mut n = text
.split(':')
.map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16));
let mut next = || {
n.next()
.and_then(Result::ok)
.with_context(|| format!("--watch {text}"))
};
let id = text
.split(':')
.next()
.and_then(|p| p.parse().ok())
.with_context(|| format!("--watch {text}"))?;
let _ = next();
watched.push((id, next()?, next()?));
}
if let Some(runs) = r
.diverge
.or(r.diverge_picture)
.or((!watched.is_empty()).then_some(2))
{
let lists = match &r.lists {
Some(text) => Some(range(text).with_context(|| format!("--lists {text}"))?),
None => None,
};
let search = play::diverge::Search {
runs: runs.max(2),
lists,
roots: r.roots,
wait_all: options.wait_all,
options: options.clone(),
};
let mut player = play::Player::load(&r.folder, &options)?;
if !watched.is_empty() {
return player.watch(&search, &watched, &mut |line| println!("{line}"));
}
if let Some(text) = &r.draws {
return player.diverge_draws(&search, text, &mut |line| println!("{line}"));
}
if r.diverge_picture.is_some() {
let commands = match &r.commands {
Some(text) => Some(range(text).with_context(|| format!("--commands {text}"))?),
None => None,
};
return player
.diverge_picture(&search, commands, r.step, &mut |line| println!("{line}"));
}
return player.diverge(&search, &mut |line| println!("{line}"));
}
let reports = play::replay(&r.folder, &options)?;
for (what, report) in &reports {
println!("{}", report.text(what));
}
if let [(_, before), (_, after)] = &reports[..] {
println!("{:+.2} ms", after.median_ms() - before.median_ms());
}
Ok(())
}
fn retranslate(folder: &std::path::Path, into: &std::path::Path, view_limit: u32, raw_views: u32) -> Result<()> {
use std::sync::atomic::{AtomicUsize, Ordering};
let wanted = play::title_shaders(folder)?;
let kept = play::find(folder)?.with_file_name("containers");
std::fs::create_dir_all(&kept)?;
std::fs::create_dir_all(into)?;
let mut missing: std::collections::HashSet<&str> = wanted
.iter()
.map(|w| w.1.as_str())
.filter(|h| !kept.join(format!("{h}.cdxil")).exists())
.collect();
if !missing.is_empty() {
println!("{} of {} containers are looked for in the title's files", missing.len(), wanted.len());
for root in crate::default_paths(Vec::new())? {
for entry in walkdir::WalkDir::new(root).into_iter().filter_map(std::result::Result::ok) {
let size = entry.metadata().map_or(0, |m| m.len());
if missing.is_empty() || !entry.file_type().is_file() || size > crate::shader::MAX_FILE {
continue;
}
let Ok(data) = std::fs::read(entry.path()) else { continue };
for source in crate::shader::sources(&data) {
let Some(bytes) = source.bytes() else { continue };
let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
if missing.remove(hash.as_str()) {
std::fs::write(kept.join(format!("{hash}.cdxil")), &bytes[..])?;
}
}
}
}
}
println!("{} containers not found", missing.len());
let wave = std::env::var("EONACAT_XS_HOST_WAVE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64);
eonacat_xsbox_gpu::shader::emit::set_host_max_wave(wave);
eonacat_xsbox_gpu::shader::emit::set_host_rdna(std::env::var_os("EONACAT_XS_HOST_RDNA").is_none_or(|v| v != "0"));
eonacat_xsbox_gpu::shader::emit::set_view_heap_limit(view_limit);
eonacat_xsbox_gpu::shader::emit::set_raw_views(raw_views);
let all: Vec<_> = wanted.iter().collect();
let (next, done) = (AtomicUsize::new(0), AtomicUsize::new(0));
let started = std::time::Instant::now();
std::thread::scope(|s| {
for _ in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) {
s.spawn(|| {
while let Some((stage, hash)) = all.get(next.fetch_add(1, Ordering::Relaxed)) {
let Ok(bytes) = std::fs::read(kept.join(format!("{hash}.cdxil"))) else { continue };
match eonacat_xsbox_gpu::shader::emit::translate(&bytes) {
Ok(t) => {
if std::fs::write(into.join(format!("{hash}.dxil")), &t.dxil).is_ok() {
done.fetch_add(1, Ordering::Relaxed);
}
}
Err(e) => println!("{stage} {hash}: {e}"),
}
}
});
}
});
println!("{} of {} shaders translated, {:.1} s", done.into_inner(), all.len(), started.elapsed().as_secs_f64());
Ok(())
}
File diff suppressed because it is too large. Load diff
+245
View File
@@ -0,0 +1,245 @@
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::path::PathBuf;
use anyhow::Result;
use eonacat_xsbox_game::sgd5;
use eonacat_xsbox_gpu::shader::gfx10::{self, Instruction};
use eonacat_xsbox_gpu::shader::{Container, DxilProgram, FourCC, HwStage, ShaderError, native_programs};
pub(crate) const MAX_FILE: u64 = 2 << 30;
pub(crate) enum Source<'a> {
Raw { offset: usize, data: &'a [u8] },
Packed(sgd5::Record<'a>),
}
impl Source<'_> {
pub(crate) fn bytes(&self) -> Option<Cow<'_, [u8]>> {
match self {
Source::Raw { data, .. } => Some(Cow::Borrowed(data)),
Source::Packed(r) => r.unpack().map(Cow::Owned),
}
}
pub(crate) fn label(&self) -> String {
match self {
Source::Raw { offset, .. } => format!("@{offset:#x}"),
Source::Packed(r) => format!("@{:#x} {}", r.offset, r.name.unwrap_or("?")),
}
}
}
pub(crate) fn sources(data: &[u8]) -> Vec<Source<'_>> {
let mut out: Vec<Source<'_>> = Vec::new();
if sgd5::is_sgd5(data) {
out.extend(sgd5::records(data).map(Source::Packed));
}
let raw = memchr::memmem::find_iter(data, b"DXBC")
.filter_map(|offset| {
let tail = &data[offset..];
let size = u32::from_le_bytes(tail.get(0x18..0x1c)?.try_into().ok()?) as usize;
let data = tail.get(..size)?;
Container::parse(data).ok()?;
Some(Source::Raw { offset, data })
});
out.extend(raw);
out
}
#[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();
let only: Option<Vec<String>> = std::env::var("EONACAT_XS_SHADER_ONLY")
.ok()
.map(|v| v.split(',').map(|h| h.trim().to_ascii_lowercase()).filter(|h| !h.is_empty()).collect());
let save = std::env::var_os("EONACAT_XS_SHADER_SAVE").map(PathBuf::from);
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 source in sources(&data) {
let Some(bytes) = source.bytes() else {
eprintln!("corrupt record {}{}", path.display(), source.label());
continue;
};
if let Some(only) = &only {
let hash = blake3::hash(&bytes).to_hex();
if !only.iter().any(|h| h == &hash[..16]) {
continue;
}
if let Some(dir) = &save {
std::fs::create_dir_all(dir)?;
std::fs::write(dir.join(format!("{}.bin", &hash[..16])), &bytes)?;
}
}
let Ok(container) = Container::parse(&bytes) else {
continue;
};
found_here += 1;
t.containers += 1;
let dxil = container.part(FourCC::DXIL).or(container.part(FourCC::ACCC));
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();
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()));
if disasm {
listing.push(format!(" {:?} stage I/O: {:?}", n.stage, n.io));
listing.extend(n.layout.iter().map(|p| format!(" {p:?}")));
listing.extend(n.used.iter().map(|u| format!(" {u:?}")));
}
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(|i| format_instruction(i, n.wave64)),
);
}
}
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 {
let hash = blake3::hash(&bytes).to_hex();
println!("{}{} #{}: {line}", path.display(), source.label(), &hash[..16]);
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, wave64: bool) -> String {
let words: Vec<_> = i.words.iter().map(|w| format!("{w:08X}")).collect();
let text = match i.name() {
Some(_) => i.text(wave64),
None => format!("<{:?} {:#x}>", i.encoding, i.opcode),
};
format!(" {:06x}: {:<44} {text}", i.offset, words.join(" "))
}
File diff suppressed because it is too large. Load diff
+489
View File
@@ -0,0 +1,489 @@
use std::collections::HashSet;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use crate::hle::known_pipelines as known;
const AT_ONCE: usize = 40;
const LONGEST: Duration = Duration::from_secs(180);
const SLOW_MS: f64 = 1000.0;
fn folder() -> Result<PathBuf> {
let cfg = eonacat_xsbox_gpu::core::Config::load()?;
Ok(cfg.cache_subdir("shaders")?.with_file_name("pipelines"))
}
fn fingerprint() -> (String, String) {
let card = eonacat_xsbox_gpu::shader::emit::host::hardware_adapter().map(|(_, name, _)| name).unwrap_or_default();
let mut h = blake3::Hasher::new();
h.update(known::fingerprint().as_bytes());
h.update(program().as_bytes());
h.update(card.as_bytes());
(h.finalize().to_hex()[..16].to_owned(), card)
}
fn program() -> String {
std::env::current_exe().map(|p| p.to_string_lossy().to_lowercase()).unwrap_or_default()
}
fn done_names<'a>(text: &'a str, marks: &str) -> HashSet<&'a str> {
text.lines().filter_map(|line| line.split_once(' ').filter(|(of, _)| *of == marks).map(|(_, name)| name)).collect()
}
fn to_make(candidates: &[usize], names: &[Option<String>], done: &HashSet<&str>, again: bool) -> (Vec<usize>, usize, usize) {
let (mut seen, mut all, mut reused, mut twins) = (HashSet::new(), Vec::new(), 0, 0);
for (&n, name) in candidates.iter().zip(names) {
match name {
Some(name) if !again && done.contains(name.as_str()) => reused += 1,
Some(name) if !seen.insert(name.as_str()) => twins += 1,
_ => all.push(n),
}
}
(all, reused, twins)
}
fn bad_keys<'a>(text: &'a str, fingerprint: &str) -> HashSet<&'a str> {
let hex = |word: &str, len| word.len() == len && word.bytes().all(|b| b.is_ascii_hexdigit());
text.lines()
.filter_map(|line| {
let mut words = line.split_whitespace();
let first = words.next()?;
let second = words.next();
let (key, recorded) = match second {
Some(key) if hex(first, 16) && hex(key, 32) => (key, Some(first)),
_ => (first, second.and_then(|word| word.strip_prefix("fp=")).filter(|fp| hex(fp, 16))),
};
(hex(key, 32) && recorded.is_none_or(|fp| fp.eq_ignore_ascii_case(fingerprint))).then_some(key)
})
.collect()
}
const USED_LIST_MIN: usize = 1000;
const ROUNDS: usize = 5;
fn used_list_min() -> usize {
std::env::var("EONACAT_XS_PRELOAD_USED_MIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(USED_LIST_MIN)
}
fn used_list_has_pipelines(list: &str, at_least: usize) -> bool {
list.lines().filter(|line| !line.trim().is_empty()).take(at_least.max(1)).count() >= at_least.max(1)
}
pub fn used_pipelines_recorded() -> Result<bool> {
let file = folder()?.join("early-pipelines.txt");
match std::fs::read_to_string(&file) {
Ok(list) => Ok(used_list_has_pipelines(&list, used_list_min())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e).with_context(|| format!("reading {}", file.display())),
}
}
pub fn run(jobs: Option<usize>, limit: Option<usize>, again: bool, used: bool, these: Option<String>) -> Result<()> {
let dir = folder()?;
if let Some(these) = these {
return make(&dir, &these);
}
let began = Instant::now();
std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
crate::hle::known_pipelines::use_translations(dir.with_file_name("shaders"));
let shared = shared_on() && used;
let (fingerprint, card) = fingerprint();
let marks = mark_fingerprint(&known::made_for(), &program(), &card, shared);
if shared_on() && !used {
println!("EONACAT_XS_WARM_SHARED applies to `warm --used` only: this warm keeps the driver's cache, as before");
}
let done_file = dir.join("warm-done.txt");
let bad_file = dir.join("warm-bad.txt");
let keys = known::keys(&dir);
let listed = std::fs::read_to_string(&done_file).unwrap_or_default();
let library_dir = library_folder(&dir, std::env::var_os("EONACAT_XS_LIBRARY_DIR"));
let library_there = !shared || library_dir.join(LIBRARY_FILE).is_file();
if !library_there {
println!("EONACAT_XS_WARM_SHARED: no {LIBRARY_FILE} in {}, earlier marks do not count", library_dir.display());
}
let done = if library_there { done_names(&listed, &marks) } else { HashSet::new() };
let listed_bad = if again || std::env::var_os("EONACAT_XS_WARM_BAD").is_some_and(|v| v == "0") {
String::new()
} else {
std::fs::read_to_string(&bad_file).unwrap_or_default()
};
let bad = bad_keys(&listed_bad, &fingerprint);
let early = std::fs::read_to_string(dir.join("early-pipelines.txt")).unwrap_or_default();
let early: HashSet<&str> = early.lines().collect();
let mut candidates: Vec<usize> = (0..keys.len())
.filter(|&n| {
let key = keys[n].as_str();
!bad.contains(key) && (!used || early.contains(key))
})
.collect();
candidates.sort_by_key(|&n| (!early.contains(keys[n].as_str()), &keys[n]));
let jobs = crate::cpu_budget::workers(jobs, Some(candidates.len()));
let naming = Instant::now();
let names = known::names(&dir, &candidates, jobs);
let unnamed = names.iter().filter(|n| n.is_none()).count();
let (mut all, reused, twins) = to_make(&candidates, &names, &done, again);
all.truncate(limit.unwrap_or(usize::MAX));
let names: std::collections::HashMap<usize, String> =
candidates.iter().copied().zip(names).filter_map(|(n, name)| Some((n, name?))).collect();
println!(
"{} pipelines known, {} to warm, named in {:.1} s ({unnamed} have no host pipeline here); \
{reused} made before by what is in them ({marks}, on {card}), {twins} the same as another, {} bad; {} to make, {jobs} processes",
keys.len(),
candidates.len(),
naming.elapsed().as_secs_f64(),
bad.len(),
all.len()
);
let total = all.len();
let state = Mutex::new((Vec::<f64>::new(), 0usize, 0usize));
let done_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&done_file)?);
let made = Mutex::new(Vec::<usize>::new());
let slow_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(dir.join("slow-pipelines.txt"))?);
let bad_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&bad_file)?);
let mut todo = all;
for round in 1..=ROUNDS {
let chunks: Vec<&[usize]> = todo.chunks(AT_ONCE).collect();
let next = AtomicUsize::new(0);
let answered = Mutex::new(HashSet::<usize>::new());
std::thread::scope(|s| {
for _ in 0..jobs.min(chunks.len()) {
s.spawn(|| {
while let Some(&chunk) = chunks.get(next.fetch_add(1, Ordering::Relaxed)) {
let mut rest = chunk;
while !rest.is_empty() {
let (made, ended) = child(rest, |n, ms, there| {
if ms >= SLOW_MS {
let _ = writeln!(lock(&slow_out), "\n{} {ms:.0}", keys[n]);
}
lock(&answered).insert(n);
let mut state = lock(&state);
state.0.push(ms);
state.1 += usize::from(!there);
let count = state.0.len();
if count.is_multiple_of(1000) {
println!("{count} of {}, {:.0} s", total, began.elapsed().as_secs_f64());
}
drop(state);
if there && shared {
lock(&made).push(n);
} else if there && let Some(name) = names.get(&n) {
let _ = writeln!(lock(&done_out), "{marks} {name}");
}
});
rest = &rest[made.min(rest.len())..];
match (ended, rest.split_first()) {
(Some(why), Some((&n, after))) => {
println!("pipeline {n} {}: {why}", keys[n]);
let _ = writeln!(lock(&bad_out), "{} fp={fingerprint} {why}", keys[n]);
lock(&answered).insert(n);
lock(&state).2 += 1;
rest = after;
}
_ => break,
}
}
}
});
}
});
let answered = answered.into_inner().unwrap_or_else(|e| e.into_inner());
let before = todo.len();
todo.retain(|n| !answered.contains(n));
if todo.is_empty() {
if round > 1 {
println!("every pipeline to make answered after {round} rounds");
}
break;
}
if todo.len() == before || round == ROUNDS {
println!("{} pipelines were not made (their processes ended early); the next preload tries them again", todo.len());
break;
}
println!("{} pipelines were not made (their processes ended early); making them again, round {} of {ROUNDS}", todo.len(), round + 1);
}
let (mut times, refused, crashed) = state.into_inner().unwrap_or_else(|e| e.into_inner());
times.sort_by(f64::total_cmp);
let at = |q: f64| times.get((times.len() as f64 * q) as usize).copied().unwrap_or(0.0);
println!(
"{} made in {:.0} s ({refused} have no host pipeline, {crashed} ended their process); ms each: median {:.1}, p90 {:.1}, p99 {:.1}, most {:.0}, sum {:.0} s",
times.len(),
began.elapsed().as_secs_f64(),
at(0.5),
at(0.9),
at(0.99),
times.last().copied().unwrap_or(0.0),
times.iter().sum::<f64>() / 1e3
);
if shared {
let mut made = made.into_inner().unwrap_or_else(|e| e.into_inner());
made.sort_unstable();
if !made.is_empty() {
fill_library(&dir, &names, &marks, &made, &done_out)?;
}
}
Ok(())
}
const LIBRARY_FILE: &str = "host-pipelines.bin";
fn library_folder(pipelines: &Path, shared_dir: Option<std::ffi::OsString>) -> PathBuf {
match shared_dir {
Some(d) if !d.is_empty() => PathBuf::from(d),
_ => pipelines.to_path_buf(),
}
}
fn shared_on() -> bool {
std::env::var_os("EONACAT_XS_WARM_SHARED").is_some_and(|v| v == "1")
}
fn mark_fingerprint(base: &str, program: &str, card: &str, shared: bool) -> String {
let mut h = blake3::Hasher::new();
h.update(base.as_bytes());
if shared {
h.update(b"shared-library");
} else {
h.update(program.as_bytes());
}
h.update(card.as_bytes());
h.finalize().to_hex()[..16].to_owned()
}
fn fill_library(
dir: &Path,
names: &std::collections::HashMap<usize, String>,
marks: &str,
made: &[usize],
done_out: &Mutex<std::fs::File>,
) -> Result<()> {
const THREADS: usize = 8;
const SAVE_EVERY: usize = 1000;
let began = Instant::now();
let cfg = eonacat_xsbox_gpu::core::Config::load()?;
known::use_library(cfg.cache_subdir("shaders")?);
let threads = std::env::var("EONACAT_XS_WARM_LIBRARY_THREADS")
.ok()
.and_then(|v| v.trim().parse::<usize>().ok())
.unwrap_or(THREADS)
.clamp(1, 16);
let (count, stored) = (AtomicUsize::new(0), AtomicUsize::new(0));
let pending = Mutex::new(Vec::<usize>::new());
let flush = || {
let taken = std::mem::take(&mut *lock(&pending));
known::keep_library();
let mut out = lock(done_out);
for name in taken.iter().filter_map(|n| names.get(n)) {
let _ = writeln!(out, "{marks} {name}");
}
};
println!("host pipeline library: making {} pipelines on {threads} threads", made.len());
std::thread::scope(|s| -> Result<()> {
for t in 0..threads {
let these: Vec<usize> = made.iter().copied().skip(t).step_by(threads).collect();
let (count, stored, pending, flush) = (&count, &stored, &pending, &flush);
spawn_library_worker(s, t, move || {
let mut last = None;
known::make(dir, &these, |n, came| match came {
None => last = Some(n),
Some((_, there)) => {
if there && last == Some(n) {
stored.fetch_add(1, Ordering::Relaxed);
lock(pending).push(n);
}
let c = count.fetch_add(1, Ordering::Relaxed) + 1;
if c.is_multiple_of(250) {
println!("{c} of {} in the library, {:.0} s", made.len(), began.elapsed().as_secs_f64());
}
if c.is_multiple_of(SAVE_EVERY) {
flush();
}
}
});
})?;
}
Ok(())
})?;
flush();
println!(
"host pipeline library: {} of {} stored and marked, {:.0} s",
stored.load(Ordering::Relaxed),
made.len(),
began.elapsed().as_secs_f64()
);
Ok(())
}
fn library_workers(jobs: Option<usize>, pipelines: usize) -> usize {
crate::cpu_budget::workers(jobs, Some(pipelines))
}
fn library_worker_name(index: usize) -> String {
format!("eonacat-xs-pipelines-warm-{index}")
}
fn spawn_library_worker<'scope, 'env>(
scope: &'scope std::thread::Scope<'scope, 'env>,
index: usize,
work: impl FnOnce() + Send + 'scope,
) -> Result<()> {
std::thread::Builder::new()
.name(library_worker_name(index))
.spawn_scoped(scope, work)
.with_context(|| format!("spawning pipeline library worker {index}"))?;
Ok(())
}
pub fn into_library(jobs: Option<usize>) -> Result<()> {
let dir = folder()?;
let cfg = eonacat_xsbox_gpu::core::Config::load()?;
known::use_library(cfg.cache_subdir("shaders")?);
let keys = known::keys(&dir);
let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default();
let (bad, early, slow) = (read("warm-bad.txt"), read("early-pipelines.txt"), read("slow-pipelines.txt"));
let bad = bad_keys(&bad, &fingerprint().0);
let early: HashSet<&str> = early.lines().collect();
let slow: HashSet<&str> = slow.lines().filter_map(|l| l.split(' ').next()).filter(|k| !k.is_empty()).collect();
let mut all: Vec<usize> = (0..keys.len())
.filter(|&n| {
let key = keys[n].as_str();
!bad.contains(key) && (early.contains(key) || slow.contains(key))
})
.collect();
all.sort_by_key(|&n| (!early.contains(keys[n].as_str()), &keys[n]));
let threads = library_workers(jobs, all.len());
println!("into the pipeline library: {} pipelines (loading and slow ones), {threads} threads", all.len());
let began = Instant::now();
let (count, made) = (AtomicUsize::new(0), AtomicUsize::new(0));
std::thread::scope(|s| -> Result<()> {
for t in 0..threads {
let these: Vec<usize> = all.iter().copied().skip(t).step_by(threads).collect();
let (count, made, total, dir) = (&count, &made, all.len(), &dir);
spawn_library_worker(s, t, move || {
known::make(dir, &these, |_, came| {
let Some((_, there)) = came else { return };
made.fetch_add(usize::from(there), Ordering::Relaxed);
let n = count.fetch_add(1, Ordering::Relaxed) + 1;
if n.is_multiple_of(500) {
println!("{n} of {total} in the library, {:.0} s", began.elapsed().as_secs_f64());
}
});
})?;
}
Ok(())
})?;
known::keep_library();
println!(
"{} of {} in the pipeline library in {:.0} s",
made.load(Ordering::Relaxed),
all.len(),
began.elapsed().as_secs_f64()
);
Ok(())
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
fn child(these: &[usize], mut each: impl FnMut(usize, f64, bool)) -> (usize, Option<String>) {
let list: Vec<String> = these.iter().map(usize::to_string).collect();
let spawned = std::env::current_exe().and_then(|exe| {
use std::os::windows::process::CommandExt;
const IDLE_PRIORITY_CLASS: u32 = 0x40;
Command::new(exe)
.args(["warm", "--these", &list.join(",")])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.creation_flags(IDLE_PRIORITY_CLASS)
.spawn()
});
let Ok(mut process) = spawned else { return (these.len(), None) };
let Some(out) = process.stdout.take() else { return (these.len(), None) };
let process = Mutex::new(process);
let (heard, over) = (Mutex::new(Instant::now()), AtomicBool::new(false));
let hung = AtomicBool::new(false);
let mut made = 0;
std::thread::scope(|s| {
s.spawn(|| {
while !over.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(500));
if lock(&heard).elapsed() > LONGEST {
hung.store(true, Ordering::Relaxed);
let _ = lock(&process).kill();
return;
}
}
});
for line in BufReader::new(out).lines().map_while(Result::ok) {
*lock(&heard) = Instant::now();
let mut words = line.split(' ');
if words.next() == Some("made")
&& let (Some(n), Some(ms), Some(there)) = (words.next(), words.next(), words.next())
&& let (Ok(n), Ok(ms)) = (n.parse(), ms.parse())
{
made += 1;
each(n, ms, there == "1");
}
}
over.store(true, Ordering::Relaxed);
});
let status = lock(&process).wait();
let well = status.as_ref().is_ok_and(|s| s.success());
if well {
return (these.len(), None);
}
let why = if hung.load(Ordering::Relaxed) {
format!("hung for {} s", LONGEST.as_secs())
} else {
status.map_or_else(|e| e.to_string(), |s| format!("{s}"))
};
(made, Some(why))
}
fn make(dir: &Path, these: &str) -> Result<()> {
let these: Vec<usize> = these.split(',').map(|n| n.parse().context("--these")).collect::<Result<_>>()?;
let cfg = eonacat_xsbox_gpu::core::Config::load()?;
crate::hle::known_pipelines::use_translations(cfg.cache_subdir("shaders")?);
let mut out = std::io::stdout();
known::make(dir, &these, |n, came| {
let told = match came {
None => writeln!(out, "at {n}"),
Some((ms, there)) => writeln!(out, "made {n} {ms:.2} {}", u8::from(there)),
};
if told.and_then(|()| out.flush()).is_err() {
std::process::exit(1);
}
});
let _ = out.flush();
std::process::exit(0)
}