mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
Merge pull request #75 from certified-retart/feat/d3d12-agility-sdk
This commit is contained in:
@@ -92,7 +92,11 @@ classes asked for, shader statistics, audio formats, crash) – the to-do list f
|
||||
Windows 10/11 x64, Rust (`stable-x86_64-pc-windows-msvc`), the Windows SDK (DXC: `dxcompiler.dll`
|
||||
+ `dxil.dll`, looked up in `Windows Kits\10\bin\<version>\x64`, next to `xcl.exe` or in
|
||||
`%XCL_DXC_DIR%`), a D3D12 GPU with Shader Model 6.6 and mesh shaders, and the system XGameRuntime
|
||||
(`System32\xgameruntime.dll`, part of Windows / Gaming Services).
|
||||
(`System32\xgameruntime.dll`, part of Windows / Gaming Services). On **Windows 10** (22H2
|
||||
KB5029331+), inbox `D3D12Core.dll` stops at SM 6.5; place the Microsoft D3D12 Agility SDK
|
||||
(`D3D12Core.dll`, plus `d3d12SDKLayers.dll` if using `XCL_D3D12_DEBUG=1`) in `D3D12\` next to
|
||||
`xcl.exe`, next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, or point `%XCL_D3D12_DIR%` at it
|
||||
(for `cargo test`, use `%LOCALAPPDATA%\XCL\D3D12\` or `%XCL_D3D12_DIR%`).
|
||||
|
||||
- **GPU:** developed on AMD RDNA4. The console's geometry and NGG programs run as a compute pass plus a
|
||||
mesh pass, so a GPU without mesh shaders draws none of them. On GPUs with 32-lane waves only
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Optional DirectX 12 Agility SDK loading via `ID3D12SDKConfiguration1`.
|
||||
//!
|
||||
//! Windows 10's inbox `System32\D3D12Core.dll` stops at Shader Model 6.5, even when
|
||||
//! the GPU and driver support SM 6.6+. Windows 10 22H2 (build 19045.3393+, KB5029331)
|
||||
//! and Windows 11 expose `ID3D12SDKConfiguration1::CreateDeviceFactory`, which loads an
|
||||
//! app-supplied Agility SDK `D3D12Core.dll` at run time without Developer Mode and
|
||||
//! without static `D3D12SDKVersion` / `D3D12SDKPath` PE exports.
|
||||
//!
|
||||
//! Search order (first folder containing a valid x64 `D3D12Core.dll` exporting
|
||||
//! `D3D12SDKVersion`):
|
||||
//! 1. `%XCL_D3D12_DIR%` (when set and non-empty),
|
||||
//! 2. `<exe_dir>\D3D12`,
|
||||
//! 3. `<exe_dir>`,
|
||||
//! 4. `%LOCALAPPDATA%\XCL\D3D12`.
|
||||
//!
|
||||
//! If no Agility SDK is found or the OS lacks `ID3D12SDKConfiguration1`, device creation
|
||||
//! falls back transparently to inbox `D3D12CreateDevice`.
|
||||
|
||||
use std::ffi::CString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use windows::core::{Interface, IUnknown, Param, GUID, PCSTR};
|
||||
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
use crate::pe::{Layout, Pe};
|
||||
|
||||
/// Environment variable overriding the Agility SDK folder.
|
||||
pub const ENV: &str = "XCL_D3D12_DIR";
|
||||
|
||||
/// Result of attempting to load the Agility SDK once for this process.
|
||||
#[derive(Debug)]
|
||||
pub enum State {
|
||||
/// Loaded through `ID3D12SDKConfiguration1::CreateDeviceFactory`.
|
||||
Loaded {
|
||||
factory: ID3D12DeviceFactory,
|
||||
version: u32,
|
||||
dir: PathBuf,
|
||||
},
|
||||
/// No Agility SDK DLL was found in any search path; inbox D3D12 will be used.
|
||||
NotFound,
|
||||
/// An Agility SDK was requested or found, but could not be activated; inbox D3D12 will be used.
|
||||
Unavailable(String),
|
||||
}
|
||||
|
||||
static STATE: OnceLock<State> = OnceLock::new();
|
||||
|
||||
/// Candidate directories in search order.
|
||||
pub(crate) fn candidates(env_override: Option<PathBuf>, exe_dir: Option<PathBuf>, local_app_data: Option<PathBuf>) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
if let Some(d) = env_override {
|
||||
if !d.as_os_str().is_empty() {
|
||||
dirs.push(d);
|
||||
// When the user explicitly sets XCL_D3D12_DIR, do not silently fall through
|
||||
// to unrelated folders if that path is wrong.
|
||||
return dirs;
|
||||
}
|
||||
}
|
||||
if let Some(d) = exe_dir {
|
||||
dirs.push(d.join("D3D12"));
|
||||
dirs.push(d);
|
||||
}
|
||||
if let Some(d) = local_app_data {
|
||||
dirs.push(d.join("XCL").join("D3D12"));
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
/// Read the exported `u32` `D3D12SDKVersion` directly from a `D3D12Core.dll` image on disk
|
||||
/// without loading or executing the DLL.
|
||||
pub(crate) fn read_sdk_version_from_bytes(bytes: &[u8]) -> Result<u32, String> {
|
||||
let pe = Pe::parse(bytes, Layout::File).map_err(|e| format!("invalid PE: {e}"))?;
|
||||
if !pe.is_dll() {
|
||||
return Err("not a DLL".into());
|
||||
}
|
||||
let exports = pe.exports().map_err(|e| format!("export table: {e}"))?.ok_or("no export table")?;
|
||||
let rva = exports
|
||||
.names
|
||||
.iter()
|
||||
.find_map(|(name, idx)| {
|
||||
if name == "D3D12SDKVersion" {
|
||||
exports.functions.get(*idx as usize).copied()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.ok_or("missing D3D12SDKVersion export")?;
|
||||
if rva == 0 || exports.is_forwarder_rva(rva) {
|
||||
return Err("invalid D3D12SDKVersion export RVA".into());
|
||||
}
|
||||
let version = pe.u32_at(rva).ok_or("D3D12SDKVersion RVA outside image")?;
|
||||
if version == 0 {
|
||||
return Err("D3D12SDKVersion is 0".into());
|
||||
}
|
||||
Ok(version)
|
||||
}
|
||||
|
||||
/// Read `D3D12SDKVersion` from `<dir>\D3D12Core.dll`.
|
||||
pub(crate) fn probe_dir(dir: &Path) -> Result<u32, String> {
|
||||
let dll = dir.join("D3D12Core.dll");
|
||||
let bytes = std::fs::read(&dll).map_err(|e| format!("{}: {e}", dll.display()))?;
|
||||
read_sdk_version_from_bytes(&bytes).map_err(|e| format!("{}: {e}", dll.display()))
|
||||
}
|
||||
|
||||
/// Encode a UTF-16 code-unit slice for `cp` as a NUL-terminated multi-byte string,
|
||||
/// rejecting unrepresentable characters and unpaired surrogates.
|
||||
pub(crate) fn encode_wide_for_code_page(wide: &[u16], cp: u32) -> Result<CString, String> {
|
||||
use windows_sys::Win32::Globalization::{WideCharToMultiByte, CP_UTF8, WC_ERR_INVALID_CHARS, WC_NO_BEST_FIT_CHARS};
|
||||
|
||||
if wide.is_empty() {
|
||||
return Err("empty Agility SDK path".into());
|
||||
}
|
||||
if wide.contains(&0) {
|
||||
return Err("Agility SDK path contains NUL".into());
|
||||
}
|
||||
let wide_len = i32::try_from(wide.len()).map_err(|_| "Agility SDK path too long")?;
|
||||
// CP_UTF8 (65001) and GB18030 (54936) forbid WC_NO_BEST_FIT_CHARS and non-null lpUsedDefaultChar.
|
||||
let utf8_like = cp == CP_UTF8 || cp == 54936;
|
||||
let flags = if utf8_like { WC_ERR_INVALID_CHARS } else { WC_NO_BEST_FIT_CHARS };
|
||||
let mut used_default = 0i32;
|
||||
let used_ptr = if utf8_like { std::ptr::null_mut() } else { &mut used_default };
|
||||
// SAFETY: `wide` is a valid non-empty slice of UTF-16 code units of length `wide_len`;
|
||||
// querying the required byte count with a null output buffer and 0 length is documented
|
||||
// by Win32, and `flags`/`used_ptr` satisfy the code page's Win32 contract.
|
||||
let needed = unsafe {
|
||||
WideCharToMultiByte(cp, flags, wide.as_ptr(), wide_len, std::ptr::null_mut(), 0, std::ptr::null(), used_ptr)
|
||||
};
|
||||
if needed <= 0 || used_default != 0 {
|
||||
return Err("could not encode Agility SDK path in active code page".into());
|
||||
}
|
||||
let mut buf = vec![0u8; needed as usize];
|
||||
used_default = 0;
|
||||
let used_ptr = if utf8_like { std::ptr::null_mut() } else { &mut used_default };
|
||||
// SAFETY: `buf` has exact length `needed` returned by the sizing call above.
|
||||
let written = unsafe {
|
||||
WideCharToMultiByte(cp, flags, wide.as_ptr(), wide_len, buf.as_mut_ptr(), needed, std::ptr::null(), used_ptr)
|
||||
};
|
||||
if written <= 0 || used_default != 0 {
|
||||
return Err("Agility SDK path contains characters not representable in the system ANSI code page".into());
|
||||
}
|
||||
buf.truncate(written as usize);
|
||||
CString::new(buf).map_err(|_| "Agility SDK path contains interior NUL".into())
|
||||
}
|
||||
|
||||
/// Trim whitespace-only paths (matching `XCL_ADAPTER` handling) while preserving non-UTF-8 paths.
|
||||
pub(crate) fn clean_env_path(val: Option<std::ffi::OsString>) -> Option<PathBuf> {
|
||||
let v = val?;
|
||||
if v.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if let Some(s) = v.to_str() {
|
||||
let trimmed = s.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
return Some(PathBuf::from(trimmed));
|
||||
}
|
||||
Some(PathBuf::from(v))
|
||||
}
|
||||
|
||||
/// Format a directory path as a null-terminated ANSI string with a trailing backslash,
|
||||
/// as required by `ID3D12SDKConfiguration1::CreateDeviceFactory`.
|
||||
pub(crate) fn format_sdk_path(dir: &Path) -> Result<CString, String> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Globalization::GetACP;
|
||||
|
||||
let mut wide: Vec<u16> = dir.as_os_str().encode_wide().collect();
|
||||
if wide.is_empty() {
|
||||
return Err("empty Agility SDK path".into());
|
||||
}
|
||||
if *wide.last().unwrap() == b'/' as u16 {
|
||||
*wide.last_mut().unwrap() = b'\\' as u16;
|
||||
} else if *wide.last().unwrap() != b'\\' as u16 {
|
||||
wide.push(b'\\' as u16);
|
||||
}
|
||||
// SAFETY: `GetACP` takes no arguments and returns the process's active ANSI code page.
|
||||
let acp = unsafe { GetACP() };
|
||||
encode_wide_for_code_page(&wide, acp)
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum DirResolution {
|
||||
Found { dir: PathBuf, version: u32 },
|
||||
NotFound,
|
||||
Unavailable(String),
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_dir(
|
||||
env_override: Option<PathBuf>,
|
||||
exe_dir: Option<PathBuf>,
|
||||
local_app_data: Option<PathBuf>,
|
||||
) -> DirResolution {
|
||||
let explicit = env_override.as_ref().is_some_and(|d| !d.as_os_str().is_empty());
|
||||
let dirs = candidates(env_override, exe_dir, local_app_data);
|
||||
|
||||
let mut last_err: Option<String> = None;
|
||||
for dir in dirs {
|
||||
let dll = dir.join("D3D12Core.dll");
|
||||
if !dll.is_file() {
|
||||
if explicit {
|
||||
return DirResolution::Unavailable(format!("{ENV}={} has no D3D12Core.dll", dir.display()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match probe_dir(&dir) {
|
||||
Ok(version) => return DirResolution::Found { dir, version },
|
||||
Err(err) => {
|
||||
last_err = Some(err);
|
||||
if explicit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match last_err {
|
||||
Some(err) => DirResolution::Unavailable(err),
|
||||
None => DirResolution::NotFound,
|
||||
}
|
||||
}
|
||||
|
||||
fn init() -> State {
|
||||
let env_dir = clean_env_path(std::env::var_os(ENV));
|
||||
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf));
|
||||
let local_app_data = clean_env_path(std::env::var_os("LOCALAPPDATA"));
|
||||
|
||||
let (dir, version) = match resolve_dir(env_dir, exe_dir, local_app_data) {
|
||||
DirResolution::Found { dir, version } => (dir, version),
|
||||
DirResolution::NotFound => return State::NotFound,
|
||||
DirResolution::Unavailable(reason) => return State::Unavailable(reason),
|
||||
};
|
||||
|
||||
// CreateDeviceFactory resolves relative SDK paths relative to the executable directory,
|
||||
// whereas probe_dir checks relative to CWD. Absolutize before passing to Win32.
|
||||
let abs_dir = std::path::absolute(&dir).unwrap_or(dir);
|
||||
let path_cstr = match format_sdk_path(&abs_dir) {
|
||||
Ok(p) => p,
|
||||
Err(err) => return State::Unavailable(err),
|
||||
};
|
||||
|
||||
match create_factory(version, &abs_dir, &path_cstr) {
|
||||
Ok(factory) => State::Loaded { factory, version, dir: abs_dir },
|
||||
Err(err) => State::Unavailable(err),
|
||||
}
|
||||
}
|
||||
|
||||
type D3D12GetInterfaceFn = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut std::ffi::c_void) -> windows::core::HRESULT;
|
||||
|
||||
unsafe fn resolve_d3d12_get_interface() -> Result<D3D12GetInterfaceFn, String> {
|
||||
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32};
|
||||
|
||||
let dll = crate::util::wide("d3d12.dll");
|
||||
let h = LoadLibraryExW(dll.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
if h.is_null() {
|
||||
return Err("failed to load d3d12.dll".into());
|
||||
}
|
||||
let sym = GetProcAddress(h, b"D3D12GetInterface\0".as_ptr())
|
||||
.ok_or_else(|| "D3D12GetInterface unavailable (update Windows 10 to 22H2 KB5029331+)".to_string())?;
|
||||
Ok(std::mem::transmute::<_, D3D12GetInterfaceFn>(sym))
|
||||
}
|
||||
|
||||
fn create_factory(version: u32, dir: &Path, path_cstr: &CString) -> Result<ID3D12DeviceFactory, String> {
|
||||
// SAFETY: `D3D12GetInterface` (resolved dynamically so pre-2004 Windows 10 builds do not
|
||||
// fail at IAT load time) writes a COM interface pointer on success into `cfg_raw`.
|
||||
// `ID3D12SDKConfiguration1::CreateDeviceFactory` takes a valid NUL-terminated ANSI path
|
||||
// with trailing backslash and returns an owned `ID3D12DeviceFactory`.
|
||||
unsafe {
|
||||
let get_iface = resolve_d3d12_get_interface()?;
|
||||
let mut cfg_raw: *mut std::ffi::c_void = std::ptr::null_mut();
|
||||
get_iface(&CLSID_D3D12SDKConfiguration, &ID3D12SDKConfiguration1::IID, &mut cfg_raw)
|
||||
.ok()
|
||||
.map_err(|e| format!("ID3D12SDKConfiguration1 unavailable (update Windows 10 to 22H2 KB5029331+): {e}"))?;
|
||||
if cfg_raw.is_null() {
|
||||
return Err("D3D12GetInterface returned null ID3D12SDKConfiguration1".into());
|
||||
}
|
||||
let cfg = ID3D12SDKConfiguration1::from_raw(cfg_raw);
|
||||
let factory: ID3D12DeviceFactory = cfg
|
||||
.CreateDeviceFactory(version, PCSTR(path_cstr.as_ptr().cast()))
|
||||
.map_err(|e| format!("CreateDeviceFactory(v{version}, {}): {e}", dir.display()))?;
|
||||
factory
|
||||
.SetFlags(D3D12_DEVICE_FACTORY_FLAG_ALLOW_RETURNING_EXISTING_DEVICE)
|
||||
.map_err(|e| format!("ID3D12DeviceFactory::SetFlags: {e}"))?;
|
||||
// Upgrade process-wide D3D12 global state before XCL creates its first device so
|
||||
// free functions not exposed on ID3D12DeviceFactory (notably
|
||||
// D3D12SerializeVersionedRootSignature for SM 6.6 directly-indexed heap flags)
|
||||
// dispatch to the Agility SDK's D3D12Core.dll rather than Windows 10's inbox DLL.
|
||||
factory
|
||||
.ApplyToGlobalState()
|
||||
.map_err(|e| format!("ID3D12DeviceFactory::ApplyToGlobalState: {e}"))?;
|
||||
Ok(factory)
|
||||
}
|
||||
}
|
||||
|
||||
/// Process-wide Agility SDK state (initialized on first D3D12 use).
|
||||
pub fn state() -> &'static State {
|
||||
STATE.get_or_init(init)
|
||||
}
|
||||
|
||||
/// Diagnostic message when a device reports Shader Model < 6.6.
|
||||
pub(crate) fn format_no_sm66_message(adapter: &str, state: &State) -> String {
|
||||
match state {
|
||||
State::Loaded { version, .. } => format!("{adapter}: no SM 6.6 (Agility SDK v{version} loaded)"),
|
||||
State::Unavailable(reason) => format!("{adapter}: no SM 6.6 (Agility SDK unavailable: {reason})"),
|
||||
State::NotFound => format!("{adapter}: no SM 6.6 (on Windows 10, set {ENV} to a D3D12 Agility SDK folder)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Active Agility SDK `(version, dir)` if loaded, otherwise `None`.
|
||||
pub fn loaded() -> Option<(u32, &'static Path)> {
|
||||
match state() {
|
||||
State::Loaded { version, dir, .. } => Some((*version, dir.as_path())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a D3D12 device through the Agility SDK factory when loaded, otherwise via
|
||||
/// inbox `D3D12CreateDevice`.
|
||||
pub fn create_device<P>(adapter: P, feature_level: D3D_FEATURE_LEVEL) -> windows::core::Result<ID3D12Device>
|
||||
where
|
||||
P: Param<IUnknown>,
|
||||
{
|
||||
let mut device: Option<ID3D12Device> = None;
|
||||
match state() {
|
||||
State::Loaded { factory, .. } => {
|
||||
// SAFETY: `factory` is a valid `ID3D12DeviceFactory` kept alive for `'static`,
|
||||
// and `device` is a valid out-pointer for `ID3D12Device`.
|
||||
unsafe { factory.CreateDevice(adapter, feature_level, &mut device)? };
|
||||
}
|
||||
_ => {
|
||||
// SAFETY: standard `D3D12CreateDevice` call with valid out-pointer.
|
||||
unsafe { D3D12CreateDevice(adapter, feature_level, &mut device)? };
|
||||
}
|
||||
}
|
||||
device.ok_or_else(|| windows::core::Error::from(windows::Win32::Foundation::E_FAIL))
|
||||
}
|
||||
|
||||
/// Retrieve a D3D12 configuration/debug interface (`ID3D12Debug`,
|
||||
/// `ID3D12DeviceRemovedExtendedDataSettings`, etc.) from the Agility SDK factory when
|
||||
/// loaded, otherwise from inbox `D3D12GetDebugInterface`.
|
||||
pub fn configuration_interface<T: Interface>(clsid: &GUID) -> windows::core::Result<T> {
|
||||
match state() {
|
||||
State::Loaded { factory, .. } => {
|
||||
// SAFETY: `factory` is a valid `ID3D12DeviceFactory` kept alive for `'static`
|
||||
// and `clsid` is a valid GUID ref. Do not fall back to global
|
||||
// `D3D12GetDebugInterface`, which configures inbox singleton state rather than
|
||||
// this factory and can remove existing singleton devices.
|
||||
unsafe { factory.GetConfigurationInterface::<T>(clsid) }
|
||||
}
|
||||
_ => {
|
||||
let mut out: Option<T> = None;
|
||||
// SAFETY: `D3D12GetDebugInterface` writes a COM interface pointer into `out` on success.
|
||||
unsafe { D3D12GetDebugInterface(&mut out)? };
|
||||
out.ok_or_else(|| windows::core::Error::from(windows::Win32::Foundation::E_NOINTERFACE))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "agility_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,245 @@
|
||||
use super::*;
|
||||
use crate::pe::{DIR_EXPORT, IMAGE_FILE_DLL, IMAGE_FILE_MACHINE_AMD64};
|
||||
|
||||
/// Build a minimal synthetic x64 PE DLL image with an optional `D3D12SDKVersion` export.
|
||||
fn synthetic_pe_dll(is_dll: bool, export_name: Option<&str>, sdk_version: Option<u32>, forwarder: bool) -> Vec<u8> {
|
||||
let mut img = vec![0u8; 0x600];
|
||||
// DOS header
|
||||
img[0..2].copy_from_slice(b"MZ");
|
||||
img[0x3C..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
// PE signature + COFF header at 0x80
|
||||
img[0x80..0x84].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x84;
|
||||
img[coff..coff + 2].copy_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes());
|
||||
img[coff + 2..coff + 4].copy_from_slice(&1u16.to_le_bytes()); // 1 section
|
||||
let opt_size: u16 = 240;
|
||||
img[coff + 16..coff + 18].copy_from_slice(&opt_size.to_le_bytes());
|
||||
let chars: u16 = if is_dll { IMAGE_FILE_DLL } else { 0 };
|
||||
img[coff + 18..coff + 20].copy_from_slice(&chars.to_le_bytes());
|
||||
|
||||
// Optional header (PE32+) at coff + 20 = 0x98
|
||||
let opt = coff + 20;
|
||||
img[opt..opt + 2].copy_from_slice(&0x20Bu16.to_le_bytes());
|
||||
img[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); // SectionAlignment
|
||||
img[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); // FileAlignment
|
||||
img[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes()); // SizeOfImage
|
||||
img[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes()); // SizeOfHeaders
|
||||
img[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); // NumberOfRvaAndSizes
|
||||
|
||||
// Section table at opt + 240 = 0x188: single .rdata section RVA 0x1000 -> file offset 0x200, size 0x400
|
||||
let sec = opt + opt_size as usize;
|
||||
img[sec..sec + 6].copy_from_slice(b".rdata");
|
||||
img[sec + 8..sec + 12].copy_from_slice(&0x400u32.to_le_bytes()); // VirtualSize
|
||||
img[sec + 12..sec + 16].copy_from_slice(&0x1000u32.to_le_bytes()); // VirtualAddress
|
||||
img[sec + 16..sec + 20].copy_from_slice(&0x400u32.to_le_bytes()); // SizeOfRawData
|
||||
img[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // PointerToRawData
|
||||
|
||||
if let Some(name) = export_name {
|
||||
// Export directory at RVA 0x1000 (file offset 0x200), size 0x100
|
||||
let dir_off = opt + 112 + DIR_EXPORT * 8;
|
||||
img[dir_off..dir_off + 4].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
img[dir_off + 4..dir_off + 8].copy_from_slice(&0x100u32.to_le_bytes());
|
||||
|
||||
let base = 0x200;
|
||||
let dll_name_rva = 0x1080u32;
|
||||
let afunc_rva = 0x1040u32;
|
||||
let anames_rva = 0x1050u32;
|
||||
let aords_rva = 0x1060u32;
|
||||
let exp_name_rva = 0x10A0u32;
|
||||
let value_rva = if forwarder { 0x10C0u32 } else { 0x1200u32 };
|
||||
|
||||
img[base + 12..base + 16].copy_from_slice(&dll_name_rva.to_le_bytes());
|
||||
img[base + 16..base + 20].copy_from_slice(&1u32.to_le_bytes()); // ordinal base
|
||||
img[base + 20..base + 24].copy_from_slice(&1u32.to_le_bytes()); // NumberOfFunctions
|
||||
img[base + 24..base + 28].copy_from_slice(&1u32.to_le_bytes()); // NumberOfNames
|
||||
img[base + 28..base + 32].copy_from_slice(&afunc_rva.to_le_bytes());
|
||||
img[base + 32..base + 36].copy_from_slice(&anames_rva.to_le_bytes());
|
||||
img[base + 36..base + 40].copy_from_slice(&aords_rva.to_le_bytes());
|
||||
|
||||
img[0x240..0x244].copy_from_slice(&value_rva.to_le_bytes());
|
||||
img[0x250..0x254].copy_from_slice(&exp_name_rva.to_le_bytes());
|
||||
img[0x260..0x262].copy_from_slice(&0u16.to_le_bytes());
|
||||
|
||||
let dll_name = b"D3D12Core.dll\0";
|
||||
img[0x280..0x280 + dll_name.len()].copy_from_slice(dll_name);
|
||||
let nb = name.as_bytes();
|
||||
img[0x2A0..0x2A0 + nb.len()].copy_from_slice(nb);
|
||||
img[0x2A0 + nb.len()] = 0;
|
||||
|
||||
if forwarder {
|
||||
let fwd = b"OTHER.D3D12SDKVersion\0";
|
||||
img[0x2C0..0x2C0 + fwd.len()].copy_from_slice(fwd);
|
||||
} else if let Some(v) = sdk_version {
|
||||
img[0x400..0x404].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_sdk_version_from_exported_symbol() {
|
||||
let bytes = synthetic_pe_dll(true, Some("D3D12SDKVersion"), Some(618), false);
|
||||
assert_eq!(read_sdk_version_from_bytes(&bytes), Ok(618));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_dll_missing_zero_and_forwarder_exports() {
|
||||
let exe = synthetic_pe_dll(false, Some("D3D12SDKVersion"), Some(618), false);
|
||||
assert!(read_sdk_version_from_bytes(&exe).is_err());
|
||||
|
||||
let no_exports = synthetic_pe_dll(true, None, None, false);
|
||||
assert!(read_sdk_version_from_bytes(&no_exports).is_err());
|
||||
|
||||
let other_export = synthetic_pe_dll(true, Some("D3D12GetInterface"), Some(618), false);
|
||||
assert!(read_sdk_version_from_bytes(&other_export).is_err());
|
||||
|
||||
let zero_ver = synthetic_pe_dll(true, Some("D3D12SDKVersion"), Some(0), false);
|
||||
assert!(read_sdk_version_from_bytes(&zero_ver).is_err());
|
||||
|
||||
let fwd = synthetic_pe_dll(true, Some("D3D12SDKVersion"), Some(618), true);
|
||||
assert!(read_sdk_version_from_bytes(&fwd).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidate_order_respects_explicit_env_override() {
|
||||
let explicit = candidates(
|
||||
Some(PathBuf::from(r"D:\custom\agility")),
|
||||
Some(PathBuf::from(r"C:\xcl")),
|
||||
Some(PathBuf::from(r"C:\Users\u\AppData\Local")),
|
||||
);
|
||||
assert_eq!(explicit, vec![PathBuf::from(r"D:\custom\agility")]);
|
||||
|
||||
let defaults = candidates(
|
||||
None,
|
||||
Some(PathBuf::from(r"C:\xcl")),
|
||||
Some(PathBuf::from(r"C:\Users\u\AppData\Local")),
|
||||
);
|
||||
assert_eq!(
|
||||
defaults,
|
||||
vec![
|
||||
PathBuf::from(r"C:\xcl\D3D12"),
|
||||
PathBuf::from(r"C:\xcl"),
|
||||
PathBuf::from(r"C:\Users\u\AppData\Local\XCL\D3D12"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_sdk_path_ensures_trailing_separator() {
|
||||
let p1 = format_sdk_path(Path::new(r"C:\agility")).unwrap();
|
||||
assert_eq!(p1.to_str().unwrap(), r"C:\agility\");
|
||||
|
||||
let p2 = format_sdk_path(Path::new(r"C:\agility\")).unwrap();
|
||||
assert_eq!(p2.to_str().unwrap(), r"C:\agility\");
|
||||
|
||||
assert!(format_sdk_path(Path::new("")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_wide_supports_utf8_and_legacy_ansi_code_pages() {
|
||||
use windows_sys::Win32::Globalization::CP_UTF8;
|
||||
|
||||
let ascii: Vec<u16> = r"C:\agility\".encode_utf16().collect();
|
||||
assert_eq!(encode_wide_for_code_page(&ascii, CP_UTF8).unwrap().to_str().unwrap(), r"C:\agility\");
|
||||
assert_eq!(encode_wide_for_code_page(&ascii, 1252).unwrap().to_str().unwrap(), r"C:\agility\");
|
||||
|
||||
// Non-ASCII Unicode succeeds under UTF-8 and is rejected without lossy replacement under 1252.
|
||||
let unicode: Vec<u16> = r"C:\ゲーム\D3D12\".encode_utf16().collect();
|
||||
assert_eq!(encode_wide_for_code_page(&unicode, CP_UTF8).unwrap().to_str().unwrap(), r"C:\ゲーム\D3D12\");
|
||||
assert!(encode_wide_for_code_page(&unicode, 1252).is_err());
|
||||
|
||||
// Unpaired UTF-16 surrogate must be rejected under UTF-8.
|
||||
let bad_surrogate: Vec<u16> = vec![b'C' as u16, b':' as u16, 0xD800, b'\\' as u16];
|
||||
assert!(encode_wide_for_code_page(&bad_surrogate, CP_UTF8).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_export_rvas_and_cross_section_reads() {
|
||||
let opt = 0x98usize;
|
||||
let dir_off = opt + 112 + DIR_EXPORT * 8;
|
||||
|
||||
// Export directory RVA near u32::MAX must not panic or wrap.
|
||||
let mut overflow_dir = synthetic_pe_dll(true, Some("D3D12SDKVersion"), Some(618), false);
|
||||
overflow_dir[dir_off..dir_off + 4].copy_from_slice(&(u32::MAX - 4).to_le_bytes());
|
||||
overflow_dir[dir_off + 4..dir_off + 8].copy_from_slice(&0x100u32.to_le_bytes());
|
||||
assert!(read_sdk_version_from_bytes(&overflow_dir).is_err());
|
||||
|
||||
// Export directory smaller than IMAGE_EXPORT_DIRECTORY (40 bytes) must be rejected.
|
||||
let mut short_dir = synthetic_pe_dll(true, Some("D3D12SDKVersion"), Some(618), false);
|
||||
short_dir[dir_off + 4..dir_off + 8].copy_from_slice(&20u32.to_le_bytes());
|
||||
assert!(read_sdk_version_from_bytes(&short_dir).is_err());
|
||||
|
||||
// D3D12SDKVersion RVA placed in the last 2 bytes of .rdata must not bleed into trailing overlay bytes.
|
||||
let mut boundary = synthetic_pe_dll(true, Some("D3D12SDKVersion"), Some(618), false);
|
||||
boundary.extend_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD]); // file overlay after .rdata
|
||||
// .rdata is RVA 0x1000..0x1400 (file 0x200..0x600); point value_rva at 0x13FE (only 2 bytes left in section)
|
||||
boundary[0x240..0x244].copy_from_slice(&0x13FEu32.to_le_bytes());
|
||||
boundary[0x5FE..0x600].copy_from_slice(&[0x6A, 0x02]);
|
||||
assert!(read_sdk_version_from_bytes(&boundary).is_err());
|
||||
|
||||
// 32-bit x86 DLL (machine 0x014C) must be rejected.
|
||||
let mut x86 = synthetic_pe_dll(true, Some("D3D12SDKVersion"), Some(618), false);
|
||||
x86[0x84..0x86].copy_from_slice(&0x014Cu16.to_le_bytes());
|
||||
assert!(read_sdk_version_from_bytes(&x86).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_trimming_trailing_slash_and_no_sm66_messages() {
|
||||
use std::ffi::OsString;
|
||||
|
||||
assert_eq!(clean_env_path(None), None);
|
||||
assert_eq!(clean_env_path(Some(OsString::from(""))), None);
|
||||
assert_eq!(clean_env_path(Some(OsString::from(" \t "))), None);
|
||||
assert_eq!(clean_env_path(Some(OsString::from(r" C:\agility "))), Some(PathBuf::from(r"C:\agility")));
|
||||
|
||||
// Trailing forward slash is normalized to a trailing backslash.
|
||||
let p = format_sdk_path(Path::new("C:/agility/")).unwrap();
|
||||
assert_eq!(p.to_str().unwrap(), r"C:/agility\");
|
||||
|
||||
let msg_not_found = format_no_sm66_message("GPU0", &State::NotFound);
|
||||
assert!(msg_not_found.contains(ENV));
|
||||
let msg_unavail = format_no_sm66_message("GPU0", &State::Unavailable("bad dll".into()));
|
||||
assert!(msg_unavail.contains("bad dll"));
|
||||
assert!(!msg_unavail.contains("on Windows 10, set"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_dir_handles_explicit_override_and_implicit_fallback() {
|
||||
let root = std::env::temp_dir().join(format!("xcl_agility_test_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let exe_dir = root.join("exe");
|
||||
let exe_d3d12 = exe_dir.join("D3D12");
|
||||
let local_app = root.join("local");
|
||||
let local_d3d12 = local_app.join("XCL").join("D3D12");
|
||||
let empty_dir = root.join("empty");
|
||||
std::fs::create_dir_all(&exe_d3d12).unwrap();
|
||||
std::fs::create_dir_all(&local_d3d12).unwrap();
|
||||
std::fs::create_dir_all(&empty_dir).unwrap();
|
||||
|
||||
// All empty -> NotFound
|
||||
assert_eq!(resolve_dir(None, Some(exe_dir.clone()), Some(local_app.clone())), DirResolution::NotFound);
|
||||
|
||||
// Explicit env override pointing at empty dir -> Unavailable (does NOT fall through to local_app)
|
||||
let valid_dll = synthetic_pe_dll(true, Some("D3D12SDKVersion"), Some(620), false);
|
||||
std::fs::write(local_d3d12.join("D3D12Core.dll"), &valid_dll).unwrap();
|
||||
assert!(matches!(
|
||||
resolve_dir(Some(empty_dir.clone()), Some(exe_dir.clone()), Some(local_app.clone())),
|
||||
DirResolution::Unavailable(_)
|
||||
));
|
||||
|
||||
// Implicit search skips bad DLL in exe\D3D12 and falls through to valid DLL in %LOCALAPPDATA%\XCL\D3D12
|
||||
std::fs::write(exe_d3d12.join("D3D12Core.dll"), b"not a pe").unwrap();
|
||||
assert_eq!(
|
||||
resolve_dir(None, Some(exe_dir.clone()), Some(local_app.clone())),
|
||||
DirResolution::Found { dir: local_d3d12.clone(), version: 620 }
|
||||
);
|
||||
|
||||
// Implicit search with only a bad DLL returns Unavailable(last_err)
|
||||
let _ = std::fs::remove_file(local_d3d12.join("D3D12Core.dll"));
|
||||
assert!(matches!(
|
||||
resolve_dir(None, Some(exe_dir.clone()), Some(local_app.clone())),
|
||||
DirResolution::Unavailable(_)
|
||||
));
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! (decoder / disassembler – the front-end of the shader recompiler).
|
||||
|
||||
pub mod adapter;
|
||||
pub mod agility;
|
||||
pub mod bvh;
|
||||
pub mod desc;
|
||||
pub mod dxbc;
|
||||
|
||||
@@ -90,14 +90,12 @@ fn init() -> Result<Gpu, String> {
|
||||
.ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?;
|
||||
(a, crate::gpu::adapter::name(&desc))
|
||||
};
|
||||
let mut dev: Option<ID3D12Device> = None;
|
||||
D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).map_err(e)?;
|
||||
let dev = dev.ok_or("no device")?;
|
||||
let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(e)?;
|
||||
let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6 };
|
||||
dev.CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &mut sm as *mut _ as _, std::mem::size_of_val(&sm) as u32)
|
||||
.map_err(|x| format!("SM 6.6: {x}"))?;
|
||||
if sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 {
|
||||
return Err(format!("{name}: no SM 6.6"));
|
||||
return Err(crate::gpu::agility::format_no_sm66_message(&name, crate::gpu::agility::state()));
|
||||
}
|
||||
let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
|
||||
dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &mut o1 as *mut _ as _, std::mem::size_of_val(&o1) as u32).map_err(e)?;
|
||||
|
||||
@@ -514,9 +514,7 @@ mod tests {
|
||||
|
||||
fn device() -> Option<(ID3D12Device, ID3D12CommandQueue)> {
|
||||
unsafe {
|
||||
let mut dev: Option<ID3D12Device> = None;
|
||||
windows::Win32::Graphics::Direct3D12::D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?;
|
||||
let dev = dev?;
|
||||
let dev = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0).ok()?;
|
||||
let queue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).ok()?;
|
||||
Some((dev, queue))
|
||||
}
|
||||
|
||||
@@ -1226,7 +1226,9 @@ pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) {
|
||||
pc::<QueryFn>(this, PC_END_QUERY)(this, h, qty, i);
|
||||
}
|
||||
|
||||
let ext = *(this as *const usize);
|
||||
let close_hr = pc::<unsafe extern "system" fn(*mut c_void) -> i32>(this, PC_CLOSE)(this);
|
||||
real::preserve_vtable(this, ext);
|
||||
if close_hr < 0 {
|
||||
return warn(&ERR, "KickoffX", format_args!("Close failed ({close_hr:#x})"));
|
||||
}
|
||||
@@ -1247,12 +1249,10 @@ pub(super) unsafe extern "system" fn kickoff_x(this: *mut c_void) {
|
||||
}
|
||||
}
|
||||
|
||||
let ext_closed = *(this as *const usize);
|
||||
let init_pso = super::pso_async::resolve_for_bind(bound_pso);
|
||||
let ext = *(this as *const usize);
|
||||
let reset_hr = pc::<unsafe extern "system" fn(*mut c_void, usize, usize) -> i32>(this, PC_RESET)(this, alloc, init_pso);
|
||||
if *(this as *const usize) != ext {
|
||||
*(this as *mut usize) = ext;
|
||||
}
|
||||
real::preserve_vtable(this, ext_closed);
|
||||
if reset_hr < 0 {
|
||||
return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})"));
|
||||
}
|
||||
@@ -1627,13 +1627,11 @@ pub(super) unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, ps
|
||||
s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE)
|
||||
};
|
||||
super::bind::reset(this, alloc);
|
||||
// the PC runtime writes its own vtable into a copy list again on Reset: keep XCL's
|
||||
// the PC runtime writes its own vtable into a list on Reset (copy lists, Agility SDK 1.620+): re-adopt it
|
||||
let ext = *(this as *const usize);
|
||||
let resolved = super::pso_async::resolve_for_bind(pso);
|
||||
let hr = pc::<unsafe extern "system" fn(*mut c_void, usize, usize) -> i32>(this, PC_RESET)(this, alloc, resolved);
|
||||
if *(this as *const usize) != ext {
|
||||
*(this as *mut usize) = ext;
|
||||
}
|
||||
real::preserve_vtable(this, ext);
|
||||
if hr >= 0 && !is_bundle && pso != 0 {
|
||||
if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) {
|
||||
if !static_bias.is_zero() && try_native_depth_bias(this, static_bias) {
|
||||
@@ -1744,7 +1742,9 @@ unsafe fn is_buffer(res: usize) -> bool {
|
||||
|
||||
/// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it)
|
||||
pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 {
|
||||
let ext = *(this as *const usize);
|
||||
let hr = pc::<unsafe extern "system" fn(*mut c_void) -> i32>(this, 9)(this);
|
||||
real::preserve_vtable(this, ext);
|
||||
if hr < 0 {
|
||||
let ty = pc::<unsafe extern "system" fn(*mut c_void) -> i32>(this, PC_GET_TYPE)(this);
|
||||
crate::xlog_warn!("D3D12.X: DMA list Close → {:#x} (PC list type {ty})", hr as u32);
|
||||
|
||||
@@ -337,24 +337,41 @@ pub fn init() -> Result<String, String> {
|
||||
}
|
||||
unsafe {
|
||||
let cfg = crate::state::config();
|
||||
match crate::gpu::agility::state() {
|
||||
crate::gpu::agility::State::Loaded { version, dir, .. } => {
|
||||
crate::xlog_info!("D3D12: Agility SDK v{version} ({})", dir.display());
|
||||
}
|
||||
crate::gpu::agility::State::Unavailable(reason) => {
|
||||
crate::xlog_warn!("D3D12: Agility SDK unavailable ({reason}) – using inbox D3D12");
|
||||
}
|
||||
crate::gpu::agility::State::NotFound => {}
|
||||
}
|
||||
let debug = cfg.d3d12_debug || std::env::var_os("XCL_D3D12_DEBUG").is_some();
|
||||
if debug {
|
||||
let mut dbg: Option<ID3D12Debug> = None;
|
||||
if D3D12GetDebugInterface(&mut dbg).is_ok() {
|
||||
if let Some(d) = dbg {
|
||||
match crate::gpu::agility::configuration_interface::<ID3D12Debug>(&CLSID_D3D12Debug) {
|
||||
Ok(d) => {
|
||||
d.EnableDebugLayer();
|
||||
crate::xlog_info!("D3D12: debug layer enabled");
|
||||
}
|
||||
Err(e) => {
|
||||
crate::xlog_warn!("D3D12: debug layer requested but unavailable: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// `XCL_DRED=1`: on a device removal the faulting address and the last GPU operations
|
||||
// (logged by `log_device_removed`); no debug layer needed. Opt-in: with it XDefiant
|
||||
// stalled in its first seconds twice.
|
||||
let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
|
||||
if std::env::var_os("XCL_DRED").is_some() && D3D12GetDebugInterface(&mut dred).is_ok() {
|
||||
if let Some(d) = dred {
|
||||
d.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
|
||||
d.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
|
||||
if std::env::var_os("XCL_DRED").is_some() {
|
||||
match crate::gpu::agility::configuration_interface::<ID3D12DeviceRemovedExtendedDataSettings>(
|
||||
&CLSID_D3D12DeviceRemovedExtendedData,
|
||||
) {
|
||||
Ok(d) => {
|
||||
d.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
|
||||
d.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
|
||||
}
|
||||
Err(e) => {
|
||||
crate::xlog_warn!("D3D12: DRED requested but unavailable: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?;
|
||||
@@ -368,18 +385,23 @@ pub fn init() -> Result<String, String> {
|
||||
list = crate::gpu::adapter::candidates(&factory, &crate::gpu::adapter::Selector::Auto);
|
||||
}
|
||||
for (adapter, desc) in list {
|
||||
if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok() {
|
||||
if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) {
|
||||
device = Some(dev);
|
||||
name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if device.is_none() {
|
||||
let warp: IDXGIAdapter = factory.EnumWarpAdapter().map_err(|e| format!("WARP: {e}"))?;
|
||||
D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut device).map_err(|e| format!("D3D12CreateDevice(WARP): {e}"))?;
|
||||
name = "WARP (software renderer)".into();
|
||||
}
|
||||
let device = device.ok_or("no device")?;
|
||||
let device = match device {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
let warp: IDXGIAdapter = factory.EnumWarpAdapter().map_err(|e| format!("WARP: {e}"))?;
|
||||
let d = crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_11_0)
|
||||
.map_err(|e| format!("D3D12 device (WARP): {e}"))?;
|
||||
name = "WARP (software renderer)".into();
|
||||
d
|
||||
}
|
||||
};
|
||||
if debug {
|
||||
// the debug layer's messages into XCL's log (they otherwise go to a debugger only)
|
||||
if let Ok(q) = device.cast::<ID3D12InfoQueue1>() {
|
||||
@@ -482,6 +504,26 @@ fn is_ext(v: usize) -> bool {
|
||||
EXTS.lock().map(|g| g.as_ref().map(|s| s.contains(&v)).unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
fn kind_of(ext: usize) -> Option<Kind> {
|
||||
CLASSES.lock().unwrap().iter().find(|c| c.ext == ext).map(|c| c.kind)
|
||||
}
|
||||
|
||||
/// If a native D3D12 method (such as `Close` or `Reset` on Agility SDK 1.620+, or copy-list
|
||||
/// `Reset`) replaced `this`'s vtable pointer with another native runtime table, adopt the
|
||||
/// new table under the same `Kind` so XCL's hooks stay installed while forwarding to the
|
||||
/// runtime's current state table.
|
||||
pub(super) unsafe fn preserve_vtable(this: *mut c_void, prev_ext: usize) {
|
||||
let cur = *(this as *const usize);
|
||||
if cur == prev_ext || is_ext(cur) {
|
||||
return;
|
||||
}
|
||||
if let Some(kind) = kind_of(prev_ext) {
|
||||
adopt(this, kind);
|
||||
} else {
|
||||
*(this as *mut usize) = prev_ext;
|
||||
}
|
||||
}
|
||||
|
||||
/// An adopted object gets the extended vtable of another kind (a DMA list: created as a PC
|
||||
/// list, it needs the console's DMA layout).
|
||||
pub(super) unsafe fn readopt(obj: *mut c_void, kind: Kind) {
|
||||
@@ -1764,6 +1806,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> {
|
||||
Kind::CommandList => v.extend_from_slice(&[
|
||||
("Release", cl_release as usize),
|
||||
("Close", cl_close as usize),
|
||||
("Reset", cl_reset as usize),
|
||||
("ClearState", cl_clear_state as usize),
|
||||
("DrawInstanced", cl_draw_instanced as usize),
|
||||
("DrawIndexedInstanced", cl_draw_indexed_instanced as usize),
|
||||
@@ -1830,10 +1873,14 @@ macro_rules! as_usize {
|
||||
}
|
||||
|
||||
/// Close: a failure is logged with what was recorded (titles stop on it; the PC runtime
|
||||
/// refuses some calls only here)
|
||||
/// refuses some calls only here). Newer D3D12 runtimes (e.g. Agility SDK 1.620+) swap the
|
||||
/// command list's vtable pointer on Close; adopt the runtime's new state vtable so
|
||||
/// subsequent Reset and console calls dispatch through the current native table.
|
||||
unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT {
|
||||
let ext = *(this as *const usize);
|
||||
let f: RefFn = std::mem::transmute(orig_fn(this, slot_of(this, "Close")));
|
||||
let hr = f(this) as HRESULT;
|
||||
preserve_vtable(this, ext);
|
||||
if hr < 0 {
|
||||
let ty: RefFn = std::mem::transmute(orig_fn(this, slot_of(this, "GetType")));
|
||||
crate::xlog_warn!("D3D12.X: command list {this:p} (type {}) Close → {:#x}", ty(this), hr as u32);
|
||||
@@ -1841,6 +1888,16 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT {
|
||||
hr
|
||||
}
|
||||
|
||||
/// Reset (PC path): re-adopt the runtime's new open-state vtable if Reset replaced it.
|
||||
unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, initial_state: *mut c_void) -> HRESULT {
|
||||
let ext = *(this as *const usize);
|
||||
let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT =
|
||||
std::mem::transmute(orig_fn(this, slot_of(this, "Reset")));
|
||||
let hr = f(this, allocator, initial_state);
|
||||
preserve_vtable(this, ext);
|
||||
hr
|
||||
}
|
||||
|
||||
/// The PC size of a CheckFeatureSupport structure.
|
||||
fn pc_feature_size(feature: i32) -> Option<usize> {
|
||||
use std::mem::size_of;
|
||||
|
||||
@@ -286,7 +286,6 @@ mod tests {
|
||||
#[test]
|
||||
fn reset_dxgi_device_manager_with_d3d12_device_and_token_validation() {
|
||||
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12CreateDevice;
|
||||
use windows::Win32::Media::MediaFoundation::{
|
||||
MFCreateDXGIDeviceManager, MFShutdown, MFStartup, MFSTARTUP_LITE, MF_VERSION,
|
||||
};
|
||||
@@ -302,12 +301,10 @@ mod tests {
|
||||
assert!(hr.is_ok(), "MFCreateDXGIDeviceManager failed: {hr:?}");
|
||||
let manager = manager.expect("manager");
|
||||
|
||||
let mut d3d12_dev: Option<ID3D12Device> = None;
|
||||
if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut d3d12_dev).is_err() {
|
||||
let Ok(d3d12_dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else {
|
||||
let _ = MFShutdown();
|
||||
return;
|
||||
}
|
||||
let d3d12_dev = d3d12_dev.expect("d3d12_dev");
|
||||
};
|
||||
|
||||
// Invalid reset token MUST be rejected.
|
||||
let bad_token = reset_token.wrapping_add(1);
|
||||
|
||||
+53
-13
@@ -183,7 +183,10 @@ impl Exports {
|
||||
}
|
||||
|
||||
pub fn is_forwarder_rva(&self, rva: u32) -> bool {
|
||||
rva >= self.dir.rva && rva < self.dir.rva.saturating_add(self.dir.size)
|
||||
self.dir
|
||||
.rva
|
||||
.checked_add(self.dir.size)
|
||||
.is_some_and(|end| rva >= self.dir.rva && rva < end)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,8 +263,9 @@ impl<'a> Pe<'a> {
|
||||
let stack_reserve = rd_u64(data, opt + 72).ok_or(t(72))?;
|
||||
let stack_commit = rd_u64(data, opt + 80).ok_or(t(80))?;
|
||||
let ndirs = (rd_u32(data, opt + 108).ok_or(t(108))? as usize).min(16);
|
||||
let max_dirs = opt_size.saturating_sub(112) / 8;
|
||||
let mut dirs = [DataDir::default(); 16];
|
||||
for (i, d) in dirs.iter_mut().enumerate().take(ndirs) {
|
||||
for (i, d) in dirs.iter_mut().enumerate().take(ndirs.min(max_dirs)) {
|
||||
let o = opt + 112 + i * 8;
|
||||
d.rva = rd_u32(data, o).ok_or(t(112))?;
|
||||
d.size = rd_u32(data, o + 4).ok_or(t(112))?;
|
||||
@@ -346,24 +350,51 @@ impl<'a> Pe<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn rva_tail(&self, rva: u32) -> Option<&'a [u8]> {
|
||||
match self.layout {
|
||||
Layout::Mapped => self.data.get(rva as usize..),
|
||||
Layout::File => {
|
||||
if rva < self.size_of_headers {
|
||||
let off = rva as usize;
|
||||
let end = off.saturating_add((self.size_of_headers - rva) as usize).min(self.data.len());
|
||||
return self.data.get(off..end);
|
||||
}
|
||||
for s in &self.sections {
|
||||
let size = s.mapped_size().max(s.raw_size);
|
||||
if rva >= s.va && rva < s.va.saturating_add(size) {
|
||||
let delta = rva - s.va;
|
||||
if delta >= s.raw_size {
|
||||
return None; // in zero-filled tail, not present in file
|
||||
}
|
||||
let off = (s.raw_ptr as usize).checked_add(delta as usize)?;
|
||||
let end = off.saturating_add((s.raw_size - delta) as usize).min(self.data.len());
|
||||
return self.data.get(off..end);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bytes_at(&self, rva: u32, len: usize) -> Option<&'a [u8]> {
|
||||
let off = self.rva_to_offset(rva)?;
|
||||
self.data.get(off..off.checked_add(len)?)
|
||||
self.rva_tail(rva)?.get(..len)
|
||||
}
|
||||
|
||||
pub fn u16_at(&self, rva: u32) -> Option<u16> {
|
||||
rd_u16(self.data, self.rva_to_offset(rva)?)
|
||||
let b = self.bytes_at(rva, 2)?;
|
||||
Some(u16::from_le_bytes([b[0], b[1]]))
|
||||
}
|
||||
pub fn u32_at(&self, rva: u32) -> Option<u32> {
|
||||
rd_u32(self.data, self.rva_to_offset(rva)?)
|
||||
let b = self.bytes_at(rva, 4)?;
|
||||
Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
pub fn u64_at(&self, rva: u32) -> Option<u64> {
|
||||
rd_u64(self.data, self.rva_to_offset(rva)?)
|
||||
let b = self.bytes_at(rva, 8)?;
|
||||
Some(u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
|
||||
}
|
||||
|
||||
pub fn cstr_at(&self, rva: u32) -> Option<String> {
|
||||
let off = self.rva_to_offset(rva)?;
|
||||
let tail = self.data.get(off..)?;
|
||||
let tail = self.rva_tail(rva)?;
|
||||
let end = tail.iter().take(4096).position(|&c| c == 0)?;
|
||||
Some(String::from_utf8_lossy(&tail[..end]).into_owned())
|
||||
}
|
||||
@@ -498,7 +529,13 @@ impl<'a> Pe<'a> {
|
||||
if d.rva == 0 || d.size == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let g = |o: u32| self.u32_at(d.rva + o).ok_or(PeError::BadRva(d.rva + o));
|
||||
if d.size < 40 || d.rva.checked_add(d.size).is_none() {
|
||||
return Err(PeError::BadRva(d.rva));
|
||||
}
|
||||
let g = |o: u32| {
|
||||
let rva = d.rva.checked_add(o).ok_or(PeError::BadRva(d.rva))?;
|
||||
self.u32_at(rva).ok_or(PeError::BadRva(rva))
|
||||
};
|
||||
let name_rva = g(12)?;
|
||||
let base = g(16)?;
|
||||
let nfunc = g(20)?.min(65536);
|
||||
@@ -508,12 +545,15 @@ impl<'a> Pe<'a> {
|
||||
let aords = g(36)?;
|
||||
let mut functions = Vec::with_capacity(nfunc as usize);
|
||||
for i in 0..nfunc {
|
||||
functions.push(self.u32_at(afunc + i * 4).ok_or(PeError::BadRva(afunc))?);
|
||||
let rva = i.checked_mul(4).and_then(|o| afunc.checked_add(o)).ok_or(PeError::BadRva(afunc))?;
|
||||
functions.push(self.u32_at(rva).ok_or(PeError::BadRva(rva))?);
|
||||
}
|
||||
let mut names = Vec::with_capacity(nnames as usize);
|
||||
for i in 0..nnames {
|
||||
let nr = self.u32_at(anames + i * 4).ok_or(PeError::BadRva(anames))?;
|
||||
let idx = self.u16_at(aords + i * 2).ok_or(PeError::BadRva(aords))?;
|
||||
let nr_rva = i.checked_mul(4).and_then(|o| anames.checked_add(o)).ok_or(PeError::BadRva(anames))?;
|
||||
let ord_rva = i.checked_mul(2).and_then(|o| aords.checked_add(o)).ok_or(PeError::BadRva(aords))?;
|
||||
let nr = self.u32_at(nr_rva).ok_or(PeError::BadRva(nr_rva))?;
|
||||
let idx = self.u16_at(ord_rva).ok_or(PeError::BadRva(ord_rva))?;
|
||||
if let Some(n) = self.cstr_at(nr) {
|
||||
names.push((n, idx));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user