From 71cc72449c1157578efa156fb0fe9b80e211f3bd Mon Sep 17 00:00:00 2001 From: Nick Stallman Date: Fri, 27 Nov 2026 09:52:43 +1100 Subject: [PATCH 1/2] lanes: check that a published texture write leaves padding, closed pages and memory past it alone The texture-publication self-test places a tiled RGBA8 100x60 texture across ordinary and write-watch title memory, learns where each texel lives from a read, closes one page, and has the GPU write the texture four times while a compute queue waits for the last write's label. Whether a published write shows in the write watch depends on the host, so only the watched pages past the texture must stay unrecorded. Co-Authored-By: Claude Fable 5.2 --- examples/lanes/README.md | 1 + examples/lanes/selftest.cpp | 195 +++++++++++++++++++++++++++++++++++- project_tuxbox/verify.py | 3 +- 3 files changed, 197 insertions(+), 2 deletions(-) diff --git a/examples/lanes/README.md b/examples/lanes/README.md index c71fb870..bc20d960 100644 --- a/examples/lanes/README.md +++ b/examples/lanes/README.md @@ -49,6 +49,7 @@ The game also imports Windows core API sets for services such as files, timing a | `gpu-indirect-dispatch` | A compute shader writes indirect dispatch arguments for 0, 1 and 2 groups. Check all 24 output words, including untouched guards. | | `dispatch-wait` | Copies a producer's word after a label wait, first at list start and then immediately after a course dispatch. Reports whether compute finished before producer submission and the word read by the CPU. | | `texture-readback` | `CopyMemoryToMemoryX` reads a guest texture into title memory | +| `texture-publication` | The GPU writes a tiled guest texture several times while a compute queue waits for the last write's label. Title memory then holds each texel in its console position. The padding between texels, a page the title closed and write-watched memory past the texture are untouched. | | `ray-tracing-builder` | `XboxBvhBuilder` builds a structure with a size report, copies it and builds it again in a batch (needs ray tracing) | | `thread-dimensions` | Slot 80 `USE_THREAD_DIMENSIONS` (`0x20`) converts thread counts using the bound PSO's `[numthreads]` and fails closed without one | | `descriptor-reclaim` | Shader-visible descriptor heap reclamation across completed batches, overlapping in-flight `Reset()`, `ClearState`, evicted-slot rebinding, and unsubmitted pin exhaustion | diff --git a/examples/lanes/selftest.cpp b/examples/lanes/selftest.cpp index a00112f6..7c3e6dfb 100644 --- a/examples/lanes/selftest.cpp +++ b/examples/lanes/selftest.cpp @@ -1379,6 +1379,197 @@ void gpu_indirect_dispatch(ID3D12Device* device) { } } +// Two adjacent allocations of title memory: ordinary read-write pages, then +// pages that record CPU writes for GetWriteWatch. +struct WatchedPair { + static constexpr size_t granule = 65536; + BYTE* base{}; + WatchedPair() { + // The address of a released reservation can be taken by another thread + // before it is allocated again in two parts, so try more than once. + for (int attempt = 0; attempt < 16 && !base; ++attempt) { + auto* probe = static_cast(VirtualAlloc(nullptr, 2 * granule, MEM_RESERVE, PAGE_NOACCESS)); + if (!probe) break; + VirtualFree(probe, 0, MEM_RELEASE); + void* plain = VirtualAlloc(probe, granule, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + void* watched = plain ? VirtualAlloc(probe + granule, granule, + MEM_COMMIT | MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) + : nullptr; + if (plain && watched) base = probe; + else if (plain) VirtualFree(plain, 0, MEM_RELEASE); + } + if (!base) throw std::runtime_error("allocate adjacent plain and write-watch title memory"); + } + ~WatchedPair() { + VirtualFree(base, 0, MEM_RELEASE); + VirtualFree(base + granule, 0, MEM_RELEASE); + } + WatchedPair(const WatchedPair&) = delete; + WatchedPair& operator=(const WatchedPair&) = delete; + BYTE* watched() const { return base + granule; } + // Pages of the write-watch half that record a write and lie at or past + // `offset` bytes into it. + ULONG_PTR written_from(size_t offset) const { + void* pages[16]; + ULONG_PTR count = std::size(pages); + DWORD granularity = 0; + if (GetWriteWatch(0, watched(), granule, pages, &count, &granularity)) + throw std::runtime_error("query the write watch"); + return std::count_if(pages, pages + count, [&](void* written) { + return static_cast(written) >= watched() + offset; + }); + } +}; + +// The GPU writes a guest texture whose tiled layout has padding between its +// texels, several times, while a compute queue waits for a label the last +// write sets. The provider publishes each write to the title's pages. It must +// put every texel where the console keeps it and change nothing else: not the +// padding, which can hold other title data, and not a page the title has +// closed. Whether a published write shows in the title's write watch depends +// on the host (Proton's kernel-tracked watch records it), so only pages past +// the texture must stay unrecorded. +void texture_publication(ID3D12Device* device) { + constexpr UINT width = 100, height = 60, pitch = 512, batches = 4; + constexpr size_t page = 4096, texture_bytes = 8 * page, words = texture_bytes / 4; + constexpr size_t rows_bytes = size_t(pitch) * height; + // The texture spans both allocations, and the title closes its third page. + constexpr size_t start = WatchedPair::granule - 4 * page, closed = 2 * page; + WatchedPair memory; + Memory label(65536); + auto* guest = reinterpret_cast(memory.base + start); + // Every word names its own place, so a read of the texture shows where the + // console keeps each texel, and no word equals a texel written below. + auto initial = [](size_t word) { return 0x80000000u | static_cast(word); }; + for (size_t word = 0; word < words; ++word) guest[word] = initial(word); + + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Layout = static_cast(0x105); + ComPtr texture; + check(method(device, device_place)(device, reinterpret_cast(guest), &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&texture)), + "place guest texture"); + D3D12_TEXTURE_COPY_LOCATION image{}, linear{}; + image.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + image.pResource = texture.Get(); + linear.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + linear.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, width, height, 1, pitch}; + + // Where each texel lives: read the texture as the title's bytes define it. + auto readback = buffer(device, D3D12_HEAP_TYPE_READBACK, rows_bytes, D3D12_RESOURCE_STATE_COPY_DEST); + Queue direct(device, D3D12_COMMAND_LIST_TYPE_DIRECT); + linear.pResource = readback.Get(); + method(direct.list.Get(), slot_copy_texture)( + direct.list.Get(), &linear, 0, 0, 0, &image, nullptr, 0); + direct.submit(); + direct.finish("reading the guest texture"); + std::vector home(size_t(width) * height); + std::vector texel(words, false); + { + D3D12_RANGE range{0, rows_bytes}, empty{}; + void* mapped{}; + check(readback->Map(0, &range, &mapped), "map texture readback"); + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + UINT value; + std::memcpy(&value, static_cast(mapped) + size_t(y) * pitch + size_t(x) * 4, 4); + const size_t word = value & 0x7fffffffu; + if (!(value & 0x80000000u) || word >= words || texel[word]) { + readback->Unmap(0, &empty); + throw std::runtime_error("the texture did not read each texel from its own guest word"); + } + texel[word] = true; + home[size_t(y) * width + x] = word; + } + readback->Unmap(0, &empty); + } + if (std::count(texel.begin(), texel.end(), false) == 0) + throw std::runtime_error("the texture layout has no padding to protect"); + + // From here on the title makes no CPU write to the watched pages, and one + // page of the texture is closed to every access. The watched pages past the + // texture carry a sentinel that must survive. + constexpr size_t watched_texture = start + texture_bytes - WatchedPair::granule; + std::memset(memory.watched() + watched_texture, 0xa5, WatchedPair::granule - watched_texture); + if (ResetWriteWatch(memory.watched(), WatchedPair::granule)) + throw std::runtime_error("reset the write watch"); + DWORD old{}; + if (!VirtualProtect(memory.base + start + closed, page, PAGE_NOACCESS, &old)) + throw std::runtime_error("close a page of the texture"); + + auto written = [](UINT batch, UINT x, UINT y) { return 0x40000000u | batch << 16 | y << 8 | x; }; + Queue compute(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); + compute.wait64(label.address(), batches); + compute.write64(label.address(8), 1); + compute.submit(); + std::vector> uploads; + std::vector> allocators; + std::vector> lists; + for (UINT batch = 1; batch <= batches; ++batch) { + std::vector rows(rows_bytes); + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + const UINT value = written(batch, x, y); + std::memcpy(rows.data() + size_t(y) * pitch + size_t(x) * 4, &value, 4); + } + uploads.push_back(buffer(device, D3D12_HEAP_TYPE_UPLOAD, rows_bytes, D3D12_RESOURCE_STATE_GENERIC_READ)); + compute_fixture::upload(uploads.back().Get(), rows.data(), rows_bytes); + allocators.emplace_back(); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocators.back())), + "create batch allocator"); + lists.push_back(open_list(device, D3D12_COMMAND_LIST_TYPE_DIRECT, allocators.back().Get())); + auto* list = lists.back().Get(); + linear.pResource = uploads.back().Get(); + method(list, slot_copy_texture)(list, &image, 0, 0, 0, &linear, nullptr, 0); + if (batch == batches) method(list, slot_write64)(list, label.address(), batches, 0, 0); + check(list->Close(), "close batch list"); + ID3D12CommandList* one[]{list}; + direct.queue->ExecuteCommandLists(1, one); + direct.signal(); + } + direct.finish("direct queue writing the guest texture"); + compute.finish("compute queue waiting for the last texture write"); + expect_value(label, 8, 1, "compute queue released by the last texture write"); + + const ULONG_PTR watched = memory.written_from(watched_texture); + if (!VirtualProtect(memory.base + start + closed, page, old, &old)) + throw std::runtime_error("reopen the closed page"); + char message[200]; + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + const size_t word = home[size_t(y) * width + x]; + const bool shut = word * 4 >= closed && word * 4 < closed + page; + const UINT expected = shut ? initial(word) : written(batches, x, y); + if (guest[word] != expected) { + std::snprintf(message, sizeof(message), + "texel (%u, %u) at guest word %zu%s: expected %#x, found %#x", x, y, word, + shut ? " in the closed page" : "", expected, guest[word]); + throw std::runtime_error(message); + } + } + for (size_t word = 0; word < words; ++word) + if (!texel[word] && guest[word] != initial(word)) { + std::snprintf(message, sizeof(message), "padding at guest word %zu changed from %#x to %#x", word, + initial(word), guest[word]); + throw std::runtime_error(message); + } + if (watched) { + std::snprintf(message, sizeof(message), + "publishing the texture recorded writes to %llu write-watch pages past the texture", + static_cast(watched)); + throw std::runtime_error(message); + } + for (size_t at = watched_texture; at < WatchedPair::granule; ++at) + if (memory.watched()[at] != 0xa5) throw std::runtime_error("title memory past the texture changed"); +} + // CopyMemoryToMemoryX reads a guest texture back into title memory, as linear // rows at the copyable footprint's pitch. void texture_readback(ID3D12Device* device) { @@ -2307,6 +2498,7 @@ constexpr Scenario scenarios[] = { {L"gpu-indirect-dispatch", gpu_indirect_dispatch}, {L"dispatch-wait", dispatch_wait}, {L"texture-readback", texture_readback}, + {L"texture-publication", texture_publication}, {L"ray-tracing-builder", ray_tracing_builder}, {L"thread-dimensions", thread_dimensions}, {L"descriptor-reclaim", descriptor_reclaim}, @@ -2371,7 +2563,8 @@ std::string narrow(const wchar_t* text) { const wchar_t* const selftest_scenarios[] = {L"labels", L"cross-queue", L"compute-frame", L"skipped-command", L"copy-memory", L"direct-copy-wait", L"shared-texture", L"indirect-dispatch", L"gpu-indirect-dispatch", - L"dispatch-wait", L"texture-readback", L"ray-tracing-builder", + L"dispatch-wait", L"texture-readback", L"texture-publication", + L"ray-tracing-builder", L"thread-dimensions", L"descriptor-reclaim", L"xbox-shader", L"wave64-shader", L"raster-tables", L"lane-spill-interp", L"wave-alloc", L"raster-samplers", L"compute-root", diff --git a/project_tuxbox/verify.py b/project_tuxbox/verify.py index 96b33928..419d5a0b 100644 --- a/project_tuxbox/verify.py +++ b/project_tuxbox/verify.py @@ -30,7 +30,7 @@ # The scenarios of `lanes.exe --selftest`, one gate each. LANES_SCENARIOS = ("labels", "cross-queue", "compute-frame", "skipped-command", "copy-memory", "shared-texture", "indirect-dispatch", "gpu-indirect-dispatch", - "dispatch-wait", "direct-copy-wait", "texture-readback", + "dispatch-wait", "direct-copy-wait", "texture-readback", "texture-publication", "ray-tracing-builder", "thread-dimensions", "descriptor-reclaim") @@ -1146,6 +1146,7 @@ def exports_receipt(_imports): "lanes-selftest-gpu-indirect-dispatch": "GPU-written arguments controlling an indirect dispatch", "lanes-selftest-dispatch-wait": "A memory wait before and after a compute dispatch", "lanes-selftest-texture-readback": "A guest texture copied back to title memory", + "lanes-selftest-texture-publication": "GPU texture writes published to title memory, leaving padding, closed pages and memory past the texture alone", "lanes-benchmark": "Lanes frame, submission, fence handover, copy and pipeline timings", "lanes-selftest-ray-tracing-builder": "Single, copied and batched builds through XboxBvhBuilder", "lanes-selftest-thread-dimensions": "Slot 80 thread-dimension dispatch converted using the bound PSO group size", From e9134b07f86b078fbe0ea14e917950985fa17d4c Mon Sep 17 00:00:00 2001 From: Nick Stallman Date: Fri, 27 Nov 2026 09:52:43 +1100 Subject: [PATCH 2/2] d3d12: publish texture writes to plain data pages with a store Under Wine the native write is a request to the server for every run of texels, even in the provider's own process. Committed read-write pages that are not write-watched now take a copy that reports a fault instead of raising it, since the title can unmap its pages after they were queried. Write-watch, copy-on-write and executable pages keep their existing writes. Co-Authored-By: Claude Fable 5.2 --- runtime/d3d12/src/device/placement.rs | 2 + .../src/device/placement/guarded_copy.rs | 70 ++++++++++++ .../d3d12/src/device/placement/writeback.rs | 49 +++++++-- runtime/d3d12/src/survey.rs | 9 +- .../tests/device/placement_guarded_copy.rs | 78 ++++++++++++++ .../src/tests/device/placement_writeback.rs | 101 ++++++++++++++++++ 6 files changed, 302 insertions(+), 7 deletions(-) create mode 100644 runtime/d3d12/src/device/placement/guarded_copy.rs create mode 100644 runtime/d3d12/src/tests/device/placement_guarded_copy.rs create mode 100644 runtime/d3d12/src/tests/device/placement_writeback.rs diff --git a/runtime/d3d12/src/device/placement.rs b/runtime/d3d12/src/device/placement.rs index 892bad10..99a83fd8 100644 --- a/runtime/d3d12/src/device/placement.rs +++ b/runtime/d3d12/src/device/placement.rs @@ -1,9 +1,11 @@ //! Keep CPU-backed tiled Xbox textures coherent with their desktop images. mod descriptors; +mod guarded_copy; mod publication; mod upload; mod writeback; pub(crate) use descriptors::{DescriptorMap, DescriptorRange, HeapViews, PlacedView, Views}; +pub(crate) use guarded_copy::recover as recover_guarded_copy; pub(crate) use publication::QueueAccess; use super::Device; diff --git a/runtime/d3d12/src/device/placement/guarded_copy.rs b/runtime/d3d12/src/device/placement/guarded_copy.rs new file mode 100644 index 00000000..0c423ba3 --- /dev/null +++ b/runtime/d3d12/src/device/placement/guarded_copy.rs @@ -0,0 +1,70 @@ +//! Store into guest pages that the title can unmap or protect at any moment. +//! +//! The title owns these pages, so a check made before a store can be stale by +//! the time the store runs. A fault inside the copy is therefore turned into a +//! failed copy by the provider's vectored exception handler, which resumes at +//! `tuxbox_guarded_copy_fault` when the faulting instruction is the store. +use windows::Win32::System::Diagnostics::Debug::CONTEXT; + +// Windows x64: rcx = destination, rdx = source, r8 = length. RSI and RDI are +// callee-saved and kept in volatile registers, so the routine never moves the +// stack and needs no unwind data. The direction flag is clear on entry. +core::arch::global_asm!( + ".globl tuxbox_guarded_copy", + ".globl tuxbox_guarded_copy_store", + ".globl tuxbox_guarded_copy_fault", + "tuxbox_guarded_copy:", + "mov r9, rsi", + "mov r10, rdi", + "mov rdi, rcx", + "mov rsi, rdx", + "mov rcx, r8", + "tuxbox_guarded_copy_store:", + "rep movsb", + "mov rsi, r9", + "mov rdi, r10", + "mov eax, 1", + "ret", + "tuxbox_guarded_copy_fault:", + "mov rsi, r9", + "mov rdi, r10", + "xor eax, eax", + "ret", +); + +unsafe extern "system" { + fn tuxbox_guarded_copy(destination: *mut u8, source: *const u8, bytes: usize) -> u32; + static tuxbox_guarded_copy_store: u8; + static tuxbox_guarded_copy_fault: u8; +} + +/// Whether a fault in the copy is caught. Without the handler a stale check +/// would crash the title, so callers keep the operating system's write. +pub(super) fn available() -> bool { + crate::survey::install_handler() +} + +/// Copy `source` to `destination`. Returns false, with part of the range +/// possibly written, when a page could not be read or written. +/// +/// # Safety +/// `source` must be readable for its whole length. `destination` may be any +/// address: it is the guest's, and the handler reports a fault on it. +pub(super) unsafe fn copy(destination: *mut u8, source: &[u8]) -> bool { + // SAFETY: the routine touches only the two ranges and volatile registers. + unsafe { tuxbox_guarded_copy(destination, source.as_ptr(), source.len()) != 0 } +} + +/// Called by the vectored exception handler for a memory fault. Resumes a +/// faulting guarded copy at its failure return. +pub(crate) fn recover(context: &mut CONTEXT) -> bool { + if context.Rip != (&raw const tuxbox_guarded_copy_store).addr() as u64 { + return false; + } + context.Rip = (&raw const tuxbox_guarded_copy_fault).addr() as u64; + true +} + +#[cfg(test)] +#[path = "../../tests/device/placement_guarded_copy.rs"] +mod tests; diff --git a/runtime/d3d12/src/device/placement/writeback.rs b/runtime/d3d12/src/device/placement/writeback.rs index 56a99a37..cc588248 100644 --- a/runtime/d3d12/src/device/placement/writeback.rs +++ b/runtime/d3d12/src/device/placement/writeback.rs @@ -219,7 +219,11 @@ fn next_bit(valid: &[u64], mut at: usize, limit: usize, set: bool) -> usize { at.min(limit) } -fn query_region(address: usize) -> Result<(usize, MEMORY_BASIC_INFORMATION)> { +/// Where a run of pages with one state and protection ends, that state, and +/// whether a plain store may publish into it. +type Region = (usize, MEMORY_BASIC_INFORMATION, bool); + +fn query_region(address: usize) -> Result { let mut info = MEMORY_BASIC_INFORMATION::default(); // SAFETY: VirtualQuery probes the address and fills a local structure. if unsafe { @@ -236,7 +240,27 @@ fn query_region(address: usize) -> Result<(usize, MEMORY_BASIC_INFORMATION)> { .checked_add(info.RegionSize) .filter(|&end| end > address) .ok_or(E_INVALIDARG)?; - Ok((end, info)) + Ok((end, info, stores_directly(&info))) +} + +/// Ordinary committed read-write data pages take a plain store. A write-watch +/// region keeps the native write, so what the title's watch records for a +/// published texture stays as it was on every host: a watch that Wine keeps +/// with page protection misses the native write but would record a store. +fn stores_directly(info: &MEMORY_BASIC_INFORMATION) -> bool { + info.State == MEM_COMMIT + && info.Protect == PAGE_READWRITE + && super::guarded_copy::available() + && !watched(info.BaseAddress) +} + +/// Whether the region records CPU writes for GetWriteWatch. The query fails on +/// a region that was not allocated with MEM_WRITE_WATCH, and with no reset +/// flag it leaves the record alone. +fn watched(base: *mut core::ffi::c_void) -> bool { + let (mut address, mut count, mut granularity) = (core::ptr::null_mut(), 1usize, 0u32); + // SAFETY: the outputs are locals sized for one address. + unsafe { GetWriteWatch(0, base, 4096, Some(&mut address), Some(&mut count), Some(&mut granularity)) == 0 } } fn mapped_region(info: &MEMORY_BASIC_INFORMATION) -> bool { @@ -249,7 +273,7 @@ fn write_mapped( base: usize, bytes: &[u8], range: Range, - region: &mut (usize, MEMORY_BASIC_INFORMATION), + region: &mut Region, ) -> Result<()> { let mut at = range.start; while at < range.end { @@ -278,11 +302,20 @@ fn write_mapped( let mut written = 0; // SAFETY: the source is an owned initialized slice. Guest mappings // remain owned by the guest until the submission fence completes. - // Use the native write for data pages so Wine doesn't repeat its - // region scan for every run. Keep the instruction-cache flush for + // Plain data pages take a store: under Wine the native write is a + // request to the server for every run, even in this process. The + // guest can still unmap the pages after the query above, so the + // store reports a fault as the native write does. Write-watch and + // copy-on-write pages keep the native write, which also saves + // Wine's region scan. Keep the instruction-cache flush for // executable mappings. unsafe { - if matches!(access, PAGE_READWRITE | PAGE_WRITECOPY) { + if region.2 { + if !super::guarded_copy::copy(addr as *mut u8, block) { + return Err(E_FAIL.into()); + } + written = block.len(); + } else if matches!(access, PAGE_READWRITE | PAGE_WRITECOPY) { let status = NtWriteVirtualMemory( GetCurrentProcess(), addr as *mut _, @@ -311,3 +344,7 @@ fn write_mapped( } Ok(()) } + +#[cfg(test)] +#[path = "../../tests/device/placement_writeback.rs"] +mod tests; diff --git a/runtime/d3d12/src/survey.rs b/runtime/d3d12/src/survey.rs index 23cfff90..44a7f9b7 100644 --- a/runtime/d3d12/src/survey.rs +++ b/runtime/d3d12/src/survey.rs @@ -17,7 +17,8 @@ use core::ptr; use std::sync::atomic::{AtomicPtr, Ordering}; use std::sync::{LazyLock, Mutex, Once}; use windows::Win32::Foundation::{ - EXCEPTION_ACCESS_VIOLATION, EXCEPTION_BREAKPOINT, EXCEPTION_ILLEGAL_INSTRUCTION, HMODULE, + EXCEPTION_ACCESS_VIOLATION, EXCEPTION_BREAKPOINT, EXCEPTION_GUARD_PAGE, EXCEPTION_ILLEGAL_INSTRUCTION, + EXCEPTION_IN_PAGE_ERROR, HMODULE, }; use windows::Win32::System::Diagnostics::Debug::{ AddVectoredExceptionHandler, EXCEPTION_POINTERS, RtlCaptureStackBackTrace, RtlPcToFileHeader, @@ -165,6 +166,12 @@ unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { } return CONTINUE_SEARCH; } + // A texture publication stores into pages the title may have just unmapped. + if matches!(record_.ExceptionCode, EXCEPTION_ACCESS_VIOLATION | EXCEPTION_IN_PAGE_ERROR | EXCEPTION_GUARD_PAGE) + && crate::device::placement::recover_guarded_copy(context) + { + return CONTINUE_EXECUTION; + } if record_.ExceptionCode == EXCEPTION_ACCESS_VIOLATION { if enabled() { describe_fault(context); diff --git a/runtime/d3d12/src/tests/device/placement_guarded_copy.rs b/runtime/d3d12/src/tests/device/placement_guarded_copy.rs new file mode 100644 index 00000000..9bc895a0 --- /dev/null +++ b/runtime/d3d12/src/tests/device/placement_guarded_copy.rs @@ -0,0 +1,78 @@ +use super::{available, copy, recover}; +use windows::Win32::System::Diagnostics::Debug::CONTEXT; +use windows::Win32::System::Memory::{ + MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_PROTECTION_FLAGS, + PAGE_READONLY, PAGE_READWRITE, VirtualAlloc, VirtualFree, VirtualProtect, +}; + +const PAGE: usize = 4096; + +struct Pages(*mut u8); + +impl Pages { + fn new(count: usize) -> Self { + // SAFETY: a fresh private allocation. + let base = unsafe { VirtualAlloc(None, count * PAGE, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) }; + assert!(!base.is_null()); + Self(base.cast()) + } + + fn bytes(&self, range: std::ops::Range) -> &[u8] { + // SAFETY: tests only read pages they left committed and readable. + unsafe { std::slice::from_raw_parts(self.0.add(range.start), range.len()) } + } +} + +impl Drop for Pages { + fn drop(&mut self) { + // SAFETY: the allocation belongs to this test. + unsafe { VirtualFree(self.0.cast(), 0, MEM_RELEASE).unwrap() }; + } +} + +#[test] +fn copies_into_writable_pages() { + let pages = Pages::new(2); + let source: Vec = (0..PAGE + 100).map(|i| (i * 7 + 1) as u8).collect(); + // SAFETY: the destination range is committed and writable. + assert!(unsafe { copy(pages.0.add(50), &source) }); + assert_eq!(pages.bytes(50..50 + source.len()), source); + assert!(pages.bytes(0..50).iter().all(|&b| b == 0)); + // An empty copy stores nothing, even at an address that is not mapped. + assert!(unsafe { copy(core::ptr::null_mut(), &[]) }); +} + +#[test] +fn a_fault_in_the_destination_fails_the_copy() { + assert!(available()); + let source = vec![0x5au8; 2 * PAGE]; + for change in 0..3 { + let pages = Pages::new(3); + let second = unsafe { pages.0.add(PAGE) }; + let mut old = PAGE_PROTECTION_FLAGS::default(); + // The middle page stops being writable after any check a caller made. + unsafe { + match change { + 0 => VirtualProtect(second.cast(), PAGE, PAGE_NOACCESS, &mut old).unwrap(), + 1 => VirtualProtect(second.cast(), PAGE, PAGE_READONLY, &mut old).unwrap(), + _ => VirtualFree(second.cast(), PAGE, MEM_DECOMMIT).unwrap(), + } + } + // SAFETY: the fault on the second page is the behaviour under test. + assert!(!unsafe { copy(pages.0.add(PAGE - 16), &source) }, "change {change}"); + // Bytes before the fault were stored, and the last page was not reached. + assert!(pages.bytes(PAGE - 16..PAGE).iter().all(|&b| b == 0x5a)); + assert!(pages.bytes(2 * PAGE..3 * PAGE).iter().all(|&b| b == 0)); + // The thread keeps working after a recovered fault. + assert!(unsafe { copy(pages.0, &source[..PAGE]) }); + } +} + +#[test] +fn only_a_fault_at_the_store_is_recovered() { + let mut context = CONTEXT::default(); + context.Rip = copies_into_writable_pages as fn() as usize as u64; + let before = context.Rip; + assert!(!recover(&mut context)); + assert_eq!(context.Rip, before); +} diff --git a/runtime/d3d12/src/tests/device/placement_writeback.rs b/runtime/d3d12/src/tests/device/placement_writeback.rs new file mode 100644 index 00000000..ceb19ecb --- /dev/null +++ b/runtime/d3d12/src/tests/device/placement_writeback.rs @@ -0,0 +1,101 @@ +use super::{query_region, write_mapped}; +use windows::Win32::System::Memory::{ + GetWriteWatch, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, + PAGE_PROTECTION_FLAGS, PAGE_READONLY, PAGE_READWRITE, VIRTUAL_ALLOCATION_TYPE, VirtualAlloc, + VirtualFree, VirtualProtect, +}; + +const PAGE: usize = 4096; +/// Allocation type that records CPU writes for GetWriteWatch. +const MEM_WRITE_WATCH: VIRTUAL_ALLOCATION_TYPE = VIRTUAL_ALLOCATION_TYPE(0x0020_0000); + +struct Pages(*mut u8); + +impl Pages { + fn new(count: usize, extra: VIRTUAL_ALLOCATION_TYPE) -> Self { + // SAFETY: a fresh private allocation. + let base = unsafe { VirtualAlloc(None, count * PAGE, MEM_COMMIT | MEM_RESERVE | extra, PAGE_READWRITE) }; + assert!(!base.is_null()); + Self(base.cast()) + } + + fn protect(&self, page: usize, protection: PAGE_PROTECTION_FLAGS) { + let mut old = PAGE_PROTECTION_FLAGS::default(); + // SAFETY: the page belongs to this allocation. + unsafe { VirtualProtect(self.0.add(page * PAGE).cast(), PAGE, protection, &mut old).unwrap() }; + } + + fn bytes(&self, range: std::ops::Range) -> &[u8] { + // SAFETY: tests only read pages they left readable. + unsafe { std::slice::from_raw_parts(self.0.add(range.start), range.len()) } + } + + /// Pages of a write-watch allocation that record a CPU write. + fn watched_writes(&self, count: usize) -> usize { + let mut addresses = [core::ptr::null_mut(); 16]; + let (mut found, mut granularity) = (addresses.len(), 0u32); + // SAFETY: the outputs are locals of the stated capacity. + let status = unsafe { + GetWriteWatch(0, self.0.cast(), count * PAGE, Some(addresses.as_mut_ptr()), Some(&mut found), Some(&mut granularity)) + }; + assert_eq!(status, 0); + found + } +} + +impl Drop for Pages { + fn drop(&mut self) { + // SAFETY: the allocation belongs to this test. + unsafe { VirtualFree(self.0.cast(), 0, MEM_RELEASE).unwrap() }; + } +} + +fn publish(pages: &Pages, bytes: &[u8], range: std::ops::Range) -> windows::core::Result<()> { + let base = pages.0.addr(); + let mut region = query_region(base + range.start)?; + write_mapped(base, bytes, range, &mut region) +} + +#[test] +fn plain_data_pages_take_a_store() { + assert!(crate::survey::install_handler()); + let pages = Pages::new(3, VIRTUAL_ALLOCATION_TYPE(0)); + assert!(query_region(pages.0.addr()).unwrap().2); + let bytes: Vec = (0..3 * PAGE).map(|i| (i % 251) as u8 + 1).collect(); + publish(&pages, &bytes, 100..2 * PAGE + 7).unwrap(); + assert_eq!(pages.bytes(100..2 * PAGE + 7), &bytes[100..2 * PAGE + 7]); + assert!(pages.bytes(0..100).iter().all(|&b| b == 0)); + assert!(pages.bytes(2 * PAGE + 7..3 * PAGE).iter().all(|&b| b == 0)); +} + +#[test] +fn a_write_watch_region_keeps_the_native_write() { + let pages = Pages::new(2, MEM_WRITE_WATCH); + assert!(!query_region(pages.0.addr()).unwrap().2); + // Asking whether the region is watched neither adds nor clears a record. + assert_eq!(pages.watched_writes(2), 0); + let bytes = vec![0x77u8; 2 * PAGE]; + publish(&pages, &bytes, 8..PAGE + 8).unwrap(); + assert_eq!(pages.bytes(8..PAGE + 8), &bytes[8..PAGE + 8]); + // A CPU write by the title is still recorded afterwards. + // SAFETY: the page is committed and writable. + unsafe { pages.0.add(PAGE + 100).write_volatile(1) }; + assert!(!query_region(pages.0.addr()).unwrap().2); + assert!(pages.watched_writes(2) >= 1); +} + +#[test] +fn closed_and_read_only_pages_are_not_stored_into() { + let pages = Pages::new(3, VIRTUAL_ALLOCATION_TYPE(0)); + let bytes = vec![0x33u8; 3 * PAGE]; + // A page with no access has no guest bytes to publish and is skipped. + pages.protect(1, PAGE_NOACCESS); + publish(&pages, &bytes, 0..3 * PAGE).unwrap(); + assert!(pages.bytes(0..PAGE).iter().all(|&b| b == 0x33)); + assert!(pages.bytes(2 * PAGE..3 * PAGE).iter().all(|&b| b == 0x33)); + pages.protect(1, PAGE_READONLY); + assert!(pages.bytes(PAGE..2 * PAGE).iter().all(|&b| b == 0)); + // A read-only page is the title's to protect: publication fails instead. + assert!(publish(&pages, &bytes, 0..3 * PAGE).is_err()); + assert!(pages.bytes(PAGE..2 * PAGE).iter().all(|&b| b == 0)); +}