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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion runtime/d3d12/src/device/heap.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! Device memory heaps and resources sharing their native GPU allocation.
mod backing;
pub(in super::super) mod backing;
mod import;
mod shadow;
mod virtual_place;
Expand Down Expand Up @@ -635,6 +635,9 @@ fn validate_shared_range(start: u64, end: u64) -> windows::core::Result<()> {
let mut region = MEMORY_BASIC_INFORMATION::default();
if unsafe { VirtualQuery(Some(cursor as _), &mut region, size_of_val(&region)) } == 0
|| region.State != MEM_COMMIT || region.Protect != PAGE_READWRITE {
if backing::is_backed_range(start, end) {
return Ok(());
}
return Err(E_INVALIDARG.into());
}
cursor = (region.BaseAddress as u64).checked_add(region.RegionSize as u64).ok_or(E_INVALIDARG)?;
Expand Down
197 changes: 195 additions & 2 deletions runtime/d3d12/src/device/heap/backing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,34 @@
//! other failure, such as pages whose backings are not contiguous, fails the
//! import.
use std::sync::OnceLock;
use windows::Win32::Foundation::{E_INVALIDARG, ERROR_NOT_FOUND, GetLastError};
use windows::Win32::Foundation::{E_INVALIDARG, ERROR_MORE_DATA, ERROR_NOT_FOUND, GetLastError};
use windows::Win32::System::Diagnostics::Debug::{ReadProcessMemory, WriteProcessMemory};
use windows::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
use windows::Win32::System::Threading::GetCurrentProcess;
use windows::core::{HRESULT, Result, s, w};

#[repr(C)]
#[derive(Clone, Copy, Default)]
struct BackingRun {
address: u64,
bytes: u64,
}

type Acquire = unsafe extern "system" fn(u64, u64, *mut u64, *mut u64) -> i32;
type AcquireRuns = unsafe extern "system" fn(u64, u64, *mut BackingRun, *mut u32, *mut u64) -> i32;
type Release = unsafe extern "system" fn(u64);

#[derive(Clone, Copy)]
pub(super) struct Exports {
acquire: Acquire,
acquire_runs: Option<AcquireRuns>,
release: Release,
}

impl Exports {
#[cfg(test)]
pub(super) fn new(acquire: Acquire, release: Release) -> Self {
Self { acquire, release }
Self { acquire, acquire_runs: None, release }
}
}

Expand All @@ -53,9 +64,12 @@ fn lookup() -> Option<Exports> {
unsafe {
let module = GetModuleHandleW(w!("xmem.dll")).ok()?;
let acquire = GetProcAddress(module, s!("TuxBoxAcquirePhysicalBacking"))?;
let acquire_runs = GetProcAddress(module, s!("TuxBoxAcquirePhysicalBackingRuns"))
.map(|proc| core::mem::transmute::<unsafe extern "system" fn() -> isize, AcquireRuns>(proc));
let release = GetProcAddress(module, s!("TuxBoxReleasePhysicalBacking"))?;
Some(Exports {
acquire: core::mem::transmute::<unsafe extern "system" fn() -> isize, Acquire>(acquire),
acquire_runs,
release: core::mem::transmute::<unsafe extern "system" fn() -> isize, Release>(release),
})
}
Expand Down Expand Up @@ -119,6 +133,185 @@ pub(super) fn acquire(base: u64, size: u64) -> Result<Backing> {
Ok(Backing { address, hold: Some(hold) })
}

fn acquire_runs(base: u64, size: u64) -> Result<Option<(Vec<BackingRun>, Hold)>> {
let Some(exports) = exports() else { return Ok(None); };
let (runs, hold) = if let Some(acquire_runs_fn) = exports.acquire_runs {
let mut runs = vec![BackingRun::default(); 8];
let mut count = runs.len() as u32;
let mut cookie = 0u64;
// SAFETY: `runs` has `count` writable entries and `count`/`cookie` are writable locals.
if unsafe { (acquire_runs_fn)(base, size, runs.as_mut_ptr(), &mut count, &mut cookie) } == 0 {
let error = unsafe { GetLastError() };
if error == ERROR_MORE_DATA && (count as usize) > runs.len() {
runs.resize(count as usize, BackingRun::default());
if unsafe { (acquire_runs_fn)(base, size, runs.as_mut_ptr(), &mut count, &mut cookie) } == 0 {
let retry_err = unsafe { GetLastError() };
if retry_err == ERROR_NOT_FOUND {
return Ok(None);
}
return Err(HRESULT::from_win32(retry_err.0).into());
}
} else if error == ERROR_NOT_FOUND {
return Ok(None);
} else {
return Err(HRESULT::from_win32(error.0).into());
}
}
let hold = Hold { release: exports.release, cookie };
if (count as usize) > runs.len() {
return Err(E_INVALIDARG.into());
}
runs.truncate(count as usize);
(runs, hold)
} else {
let (mut address, mut cookie) = (0u64, 0u64);
// SAFETY: both outputs are writable locals.
if unsafe { (exports.acquire)(base, size, &mut address, &mut cookie) } == 0 {
let error = unsafe { GetLastError() };
if error == ERROR_NOT_FOUND {
return Ok(None);
}
return Err(HRESULT::from_win32(error.0).into());
}
let hold = Hold { release: exports.release, cookie };
(vec![BackingRun { address, bytes: size }], hold)
};
let mut covered = 0u64;
for run in &runs {
if run.address == 0 || !run.address.is_multiple_of(65536) || run.bytes == 0 {
return Err(E_INVALIDARG.into());
}
covered = covered.checked_add(run.bytes).ok_or(E_INVALIDARG)?;
}
if covered != size {
return Err(E_INVALIDARG.into());
}
Ok(Some((runs, hold)))
}

pub(in super::super) fn is_backed_range(start: u64, end: u64) -> bool {
if end <= start {
return false;
}
let page_start = start & !0xffff;
let Some(page_end) = end.checked_next_multiple_of(65536) else {
return false;
};
matches!(acquire_runs(page_start, page_end - page_start), Ok(Some(_)))
}

pub(in super::super) fn try_read_xmem_bytes(address: u64, dst: &mut [u8]) -> Option<bool> {
if dst.is_empty() {
return Some(true);
}
let end = address.checked_add(dst.len() as u64)?;
let page_start = address & !0xffff;
let page_end = end.checked_next_multiple_of(65536)?;
let (runs, _hold) = match acquire_runs(page_start, page_end - page_start) {
Ok(Some(ok)) => ok,
Ok(None) => return None,
Err(_) => return Some(false),
};
let mut guest_cursor = page_start;
let mut copied_total = 0usize;
for run in runs {
let Some(guest_next) = guest_cursor.checked_add(run.bytes) else {
return Some(false);
};
let copy_lo = guest_cursor.max(address);
let copy_hi = guest_next.min(end);
if copy_lo < copy_hi {
let len = (copy_hi - copy_lo) as usize;
let dst_off = (copy_lo - address) as usize;
let src_addr = run.address + (copy_lo - guest_cursor);
let mut got = 0usize;
let res = unsafe {
ReadProcessMemory(
GetCurrentProcess(),
src_addr as *const _,
dst[dst_off..dst_off + len].as_mut_ptr().cast(),
len,
Some(&mut got),
)
};
if res.is_err() || got != len {
return Some(false);
}
copied_total += got;
}
guest_cursor = guest_next;
}
Some(copied_total == dst.len())
}

pub(in super::super) fn read_guest_bytes(address: u64, dst: &mut [u8]) -> bool {
if let Some(ok) = try_read_xmem_bytes(address, dst) {
return ok;
}
if dst.is_empty() {
return true;
}
let mut got = 0usize;
let res = unsafe {
ReadProcessMemory(
GetCurrentProcess(),
address as *const _,
dst.as_mut_ptr().cast(),
dst.len(),
Some(&mut got),
)
};
res.is_ok() && got == dst.len()
}

pub(in super::super) fn try_write_xmem_bytes(address: u64, src: &[u8]) -> Option<Result<()>> {
if src.is_empty() {
return Some(Ok(()));
}
let Some(end) = address.checked_add(src.len() as u64) else {
return Some(Err(E_INVALIDARG.into()));
};
let page_start = address & !0xffff;
let Some(page_end) = end.checked_next_multiple_of(65536) else {
return Some(Err(E_INVALIDARG.into()));
};
let (runs, _hold) = match acquire_runs(page_start, page_end - page_start) {
Ok(Some(ok)) => ok,
Ok(None) => return None,
Err(error) => return Some(Err(error)),
};
let mut guest_cursor = page_start;
for run in runs {
let Some(guest_next) = guest_cursor.checked_add(run.bytes) else {
return Some(Err(E_INVALIDARG.into()));
};
let copy_lo = guest_cursor.max(address);
let copy_hi = guest_next.min(end);
if copy_lo < copy_hi {
let len = (copy_hi - copy_lo) as usize;
let src_off = (copy_lo - address) as usize;
let dst_addr = run.address + (copy_lo - guest_cursor);
let mut written = 0usize;
if let Err(err) = unsafe {
WriteProcessMemory(
GetCurrentProcess(),
dst_addr as *const _,
src[src_off..src_off + len].as_ptr().cast(),
len,
Some(&mut written),
)
} {
return Some(Err(err));
}
if written != len {
return Some(Err(windows::Win32::Foundation::E_FAIL.into()));
}
}
guest_cursor = guest_next;
}
Some(Ok(()))
}

#[cfg(test)]
#[path = "../../tests/device/heap_backing.rs"]
mod tests;
18 changes: 3 additions & 15 deletions runtime/d3d12/src/device/placement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak};
use tuxbox_xg_layout::{Desc, Plane};
use windows::Win32::Foundation::{E_INVALIDARG, E_NOTIMPL, E_OUTOFMEMORY, E_POINTER};
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::System::{Diagnostics::Debug::ReadProcessMemory, Threading::GetCurrentProcess};
use windows::core::{HRESULT, Result};

pub(crate) fn supported_state(state: D3D12_RESOURCE_STATES, flags: D3D12_RESOURCE_FLAGS) -> bool {
Expand Down Expand Up @@ -328,22 +327,11 @@ impl Texture {
let size = (mip.source.end - mip.source.start) as usize;
output.clear();
output.try_reserve_exact(size).map_err(|_| E_OUTOFMEMORY)?;
let mut copied = 0;
// SAFETY: the OS checks the guest mapping. A partial transfer never
// exposes uninitialized bytes, including when pages are decommitted.
let result = unsafe {
ReadProcessMemory(
GetCurrentProcess(),
(self.address + mip.source.start) as *const _,
output.as_mut_ptr().cast(),
size,
Some(&mut copied),
)
};
if result.is_err() || copied != size {
output.resize(size, 0);
if !super::heap::backing::read_guest_bytes(self.address + mip.source.start, output) {
output.clear();
return Ok(false);
}
unsafe { output.set_len(size) };
Ok(true)
}

Expand Down
5 changes: 5 additions & 0 deletions runtime/d3d12/src/device/placement/writeback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@ fn write_mapped(
range: Range<usize>,
region: &mut (usize, MEMORY_BASIC_INFORMATION),
) -> Result<()> {
if let Some(addr) = base.checked_add(range.start)
&& let Some(result) = super::super::heap::backing::try_write_xmem_bytes(addr as u64, &bytes[range.start..range.end])
{
return result;
}
let mut at = range.start;
while at < range.end {
let addr = base.checked_add(at).ok_or(E_INVALIDARG)?;
Expand Down
10 changes: 10 additions & 0 deletions runtime/d3d12/src/device/views/mirrors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ impl CbvMirror {
if self.mapped == 0 || self.capacity == 0 {
return 0;
}
// SAFETY: `self.mapped` points to `self.capacity` writable mapped upload bytes.
let dst_slice = unsafe { core::slice::from_raw_parts_mut(self.mapped as *mut u8, self.capacity) };
if matches!(super::super::heap::backing::try_read_xmem_bytes(self.guest, dst_slice), Some(true)) {
return self.capacity;
}
let readable = readable_prefix(self.guest, self.capacity);
// SAFETY: readable_prefix stopped at the first page that is not a
// committed readable guest mapping. `mapped` covers `capacity` bytes.
Expand Down Expand Up @@ -242,6 +247,11 @@ impl SrvMirror {
if self.mapped == 0 || self.capacity == 0 {
return 0;
}
// SAFETY: `self.mapped` points to `self.capacity` writable mapped upload bytes.
let dst_slice = unsafe { core::slice::from_raw_parts_mut(self.mapped as *mut u8, self.capacity) };
if matches!(super::super::heap::backing::try_read_xmem_bytes(self.guest, dst_slice), Some(true)) {
return self.capacity;
}
let readable = readable_prefix(self.guest, self.capacity);
unsafe {
let dst = self.mapped as *mut u8;
Expand Down
2 changes: 1 addition & 1 deletion runtime/xmem/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ publish.workspace = true
crate-type = ["staticlib"]

[dependencies]
windows-sys = { workspace = true, features = ["Win32_Foundation", "Wdk_Foundation", "Win32_Security", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Diagnostics_Debug", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_System_SystemServices"] }
windows-sys = { workspace = true, features = ["Win32_Foundation", "Wdk_Foundation", "Win32_Security", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_System_SystemServices"] }
Loading
Loading