mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
agility: trim env path, absolutize relative paths, dynamic D3D12GetInterface, and expand tests
This commit is contained in:
@@ -94,8 +94,9 @@ Windows 10/11 x64, Rust (`stable-x86_64-pc-windows-msvc`), the Windows SDK (DXC:
|
||||
`%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). On **Windows 10** (22H2
|
||||
KB5029331+), inbox `D3D12Core.dll` stops at SM 6.5; place the Microsoft D3D12 Agility SDK
|
||||
(`D3D12Core.dll`) in `D3D12\` next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, or point
|
||||
`%XCL_D3D12_DIR%` at it.
|
||||
(`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. GPUs with 32-lane waves only (NVIDIA)
|
||||
|
||||
@@ -143,6 +143,22 @@ pub(crate) fn encode_wide_for_code_page(wide: &[u16], cp: u32) -> Result<CString
|
||||
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> {
|
||||
@@ -153,7 +169,9 @@ pub(crate) fn format_sdk_path(dir: &Path) -> Result<CString, String> {
|
||||
if wide.is_empty() {
|
||||
return Err("empty Agility SDK path".into());
|
||||
}
|
||||
if *wide.last().unwrap() != b'\\' as u16 && *wide.last().unwrap() != b'/' as u16 {
|
||||
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.
|
||||
@@ -161,28 +179,32 @@ pub(crate) fn format_sdk_path(dir: &Path) -> Result<CString, String> {
|
||||
encode_wide_for_code_page(&wide, acp)
|
||||
}
|
||||
|
||||
fn init() -> State {
|
||||
let env_dir = std::env::var_os(ENV).filter(|v| !v.is_empty()).map(PathBuf::from);
|
||||
let explicit = env_dir.is_some();
|
||||
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf));
|
||||
let local_app_data = std::env::var_os("LOCALAPPDATA").filter(|v| !v.is_empty()).map(PathBuf::from);
|
||||
let dirs = candidates(env_dir, exe_dir, local_app_data);
|
||||
#[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 found: Option<(PathBuf, u32)> = None;
|
||||
let mut last_err: Option<String> = None;
|
||||
for dir in dirs {
|
||||
let dll = dir.join("D3D12Core.dll");
|
||||
if !dll.is_file() {
|
||||
if explicit {
|
||||
return State::Unavailable(format!("{ENV}={} has no D3D12Core.dll", dir.display()));
|
||||
return DirResolution::Unavailable(format!("{ENV}={} has no D3D12Core.dll", dir.display()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match probe_dir(&dir) {
|
||||
Ok(ver) => {
|
||||
found = Some((dir, ver));
|
||||
break;
|
||||
}
|
||||
Ok(version) => return DirResolution::Found { dir, version },
|
||||
Err(err) => {
|
||||
last_err = Some(err);
|
||||
if explicit {
|
||||
@@ -192,33 +214,67 @@ fn init() -> State {
|
||||
}
|
||||
}
|
||||
|
||||
let Some((dir, version)) = found else {
|
||||
return match last_err {
|
||||
Some(err) => State::Unavailable(err),
|
||||
None => State::NotFound,
|
||||
};
|
||||
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),
|
||||
};
|
||||
|
||||
let path_cstr = match format_sdk_path(&dir) {
|
||||
// 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, &dir, &path_cstr) {
|
||||
Ok(factory) => State::Loaded { factory, version, dir },
|
||||
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` writes a COM interface pointer on success into `cfg`.
|
||||
// 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 mut cfg: Option<ID3D12SDKConfiguration1> = None;
|
||||
D3D12GetInterface(&CLSID_D3D12SDKConfiguration, &mut cfg)
|
||||
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}"))?;
|
||||
let cfg = cfg.ok_or_else(|| "D3D12GetInterface returned null ID3D12SDKConfiguration1".to_string())?;
|
||||
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()))?;
|
||||
@@ -241,6 +297,15 @@ 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() {
|
||||
|
||||
@@ -176,4 +176,70 @@ fn rejects_malformed_export_rvas_and_cross_section_reads() {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ fn init() -> Result<Gpu, String> {
|
||||
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 (on Windows 10, set {} to a D3D12 Agility SDK folder)", crate::gpu::agility::ENV));
|
||||
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)?;
|
||||
|
||||
@@ -346,20 +346,30 @@ pub fn init() -> Result<String, String> {
|
||||
}
|
||||
let debug = cfg.d3d12_debug || std::env::var_os("XCL_D3D12_DEBUG").is_some();
|
||||
if debug {
|
||||
if let Ok(d) = crate::gpu::agility::configuration_interface::<ID3D12Debug>(&CLSID_D3D12Debug) {
|
||||
d.EnableDebugLayer();
|
||||
crate::xlog_info!("D3D12: debug layer enabled");
|
||||
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.
|
||||
if std::env::var_os("XCL_DRED").is_some() {
|
||||
if let Ok(d) = crate::gpu::agility::configuration_interface::<ID3D12DeviceRemovedExtendedDataSettings>(
|
||||
match crate::gpu::agility::configuration_interface::<ID3D12DeviceRemovedExtendedDataSettings>(
|
||||
&CLSID_D3D12DeviceRemovedExtendedData,
|
||||
) {
|
||||
d.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
|
||||
d.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
|
||||
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}"))?;
|
||||
@@ -380,15 +390,16 @@ pub fn init() -> Result<String, String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if device.is_none() {
|
||||
let warp: IDXGIAdapter = factory.EnumWarpAdapter().map_err(|e| format!("WARP: {e}"))?;
|
||||
device = Some(
|
||||
crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_11_0)
|
||||
.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>() {
|
||||
|
||||
Reference in New Issue
Block a user