diff --git a/docs/experiments/startup-view-token-guarded.md b/docs/experiments/startup-view-token-guarded.md new file mode 100644 index 0000000000..f8a7840b1b --- /dev/null +++ b/docs/experiments/startup-view-token-guarded.md @@ -0,0 +1,77 @@ +# View token written under an exception guard (opt-in) + +A view call (device slots 17–22) ends in `note_view` (`d3d12_capture.inl`), which writes a 32-byte token (16 bytes +for a sampler) into the title's descriptor memory, so that descriptor copies the title makes itself can be followed. +The write is preceded by `x2w_local::writable`: `commit_lazy` (with `X2W_XMEM_LAZY_COMMIT`, `x2w_xmem_commit_range`, +which takes xmem's commit mutex) and then a `VirtualQuery`. The destination is always inside a registered descriptor +range (`title_backed`). Late in the main executable's load the title creates about 10^5 views per second, from five +recording threads at once. + +## What the switch changes + +- `X2W_D3D12_VIEW_TOKEN_GUARDED=1`: the token is written by `write_view_token` under `__try`, without the commit call + and the query. A page that refuses the write (no access, read-only, a guard page, an in-page error) leaves the + descriptor without a token, as `writable` returning false did; a guard page has its guard bit set again, on that + page only, as `probe_readable` does. +- Lazy commit: with `X2W_XMEM_LAZY_COMMIT`, xmem's vectored handler commits a page on the first touch, before the + `__except` filter sees the fault. Only the startup runs below exercise this; the fixture commits its memory up + front and loads no xmem.dll. +- Concurrency: between the fault that clears a guard bit and the re-arm, another thread's write to that page goes + through, where `writable` would have refused it. The runs below refused no write, so it did not occur there. +- Only a token that lies inside one 4 KiB page takes the guarded write, so a refusal comes on its first byte and + changes nothing. A descriptor heap's title backing has no alignment check, so a token can cross a page boundary; + such a token keeps the full-span `writable` check, with or without the switch. +- With the switch set, the render totals are followed every 300 frames by + `x2w-render view tokens (X2W_D3D12_VIEW_TOKEN_GUARDED): written N, refused M`. +- Unset, the check and the write are as before. +- Only the token write changes; the view record, the shadow slot and the view references are untouched. + +## Fixture + +```powershell +ctest --preset dev --no-tests=error -j 1 -R '^startup_view_token_' -V +``` + +`startup_view_token_{unset,set}_{warp,hardware}` (`tests/startup_view_token.cpp`) creates three descriptor heaps over +title memory the fixture owns and, after creation, makes the second read-only and gives the third a guard page. A +texture SRV goes into each heap, and a second one into the writable heap. In both modes the writable heap holds both +tokens, the read-only heap stays zero and the process keeps running, and the guard page keeps its guard bit and stays +zero. Two more heaps start 16 bytes before a page boundary, so their first token crosses into a read-only page or a +guard page: in both modes the 16-byte writable prefix keeps its bytes, the left page stays `PAGE_READWRITE` without +a guard bit, and the right page keeps its protection and stays zero. The fixture-only export +`x2w_d3d12_view_token_writes` reports the guarded writes: unset `0, 0`, set `2, 2` (crossing tokens are not +guarded writes). Mutants: ignoring the switch fails `the guarded path did not write 2 tokens and refuse 2`; not +setting the guard bit again fails `the guard page lost its guard bit`; setting it again over the whole region +(`info.BaseAddress`, `info.RegionSize`) fails `the page after the guard page changed its protection`; guarding +crossing tokens too fails +`a crossing heap's writable prefix changed` (read-only right page) and leaves the left page `0x104` +(`PAGE_READWRITE | PAGE_GUARD`, guard right page). + +## Startup run of the main executable + +Local diagnostic runs, Windows 10 22H2 (19045), i7-4790K (4 cores, 8 threads), 16 GB, RTX 3080 Ti, NVIDIA driver +32.0.16.1047. Release build of this change on `main` `36d2cbeb`, warm shader cache (revision 29), scripted input, +250 s. `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1`, `X2W_D3D12_TABLE_ALIAS=1` and `X2W_D3D12_ROOT_SRV_AT_DRAW=1` in every +run; only this switch differs. Two pairs, the second in reverse order. Aggregates only; logs stay local. + +| 150–240 s | switch unset | switch set | +|---|---|---| +| mean fps, pair 1 / pair 2 | 15.5 / 15.1 | 16.6 / 15.6 | +| time in view calls (threads); µs per call | 1.19 / 1.20; 10.4 / 11.2 | 0.88 / 0.92; 7.0 / 6.7 | +| view calls per second | 114k / 107k | 126k / 136k | +| null bindings `buffer`; device removal | 0; none | 0; none | +| null bindings `token` per 1,000 translated draws | 25.7 / 23.5 | 33.6 / 30.1 | +| process commit peak | 19.3 / 18.9 GiB | 19.6 / 19.4 GiB | + +- A view call costs about 3.6 µs less. In a breakdown of a view call on the same machine, the `writable` check was + about a third of its time. +- Why it shows in the frame rate: five recording threads draw the late load. A thread-state sample of them + (`NtQuerySystemInformation`, every 20 ms) found them runnable but without a free core in 14–21% of the samples, + so CPU time they save is CPU time they use for the next lists. +- A confirmation run with the switch set (the report line above) logged `written 16447410, refused 0`: the guard + refused no write. That shows no token was lost to a refusal, not that every token matches the default path. +- The `token` null bindings were higher with the switch (33.6 / 30.1 against 25.7 / 23.5 per 1,000 translated + draws). Runs without this change gave 23–34 per 1,000 on the same machine, so the difference lies within that + spread, but it is not explained. + +Not established: other adapters and drivers, hosts with more cores, and Wine (where #2911 changes `writable`). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 852a25b959..1844a67260 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1644,6 +1644,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | +| `X2W_D3D12_VIEW_TOKEN_GUARDED=1` | opt-in, render mode: the view token that a view call (device slots 17–22) writes into title descriptor memory is written under an exception guard instead of after `commit_lazy` and a `VirtualQuery` per view (default). A page that refuses the write (no access, read-only, a guard page, whose guard bit is set again, an in-page error) leaves the descriptor without a token, as before; a token that crosses a page boundary keeps the check (`startup_view_token_*`). See [the experiment note](experiments/startup-view-token-guarded.md) | | `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` | opt-in, render mode: a closed command list releases its upload ring chunks once its submit is fenced instead of holding them until Reset, and the ring grows in 16 MiB chunks up to 512 MiB (default: doubling chunks up to 256 MiB, holds until Reset). The larger ring can add up to about 1 GiB of process commit at peak (startup runs in the experiment note). A later submit of the same list before its Reset fences its unchanged chunks again; if one was reused in between, that list is refused before the execute and logged (`startup_address_console_gate_ring_keep_*`, `upload_reservation`). See [the experiment note](experiments/startup-upload-ring-release-at-submit.md) | | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the confirmed `BeginQuery`, `EndQuery` and `ResolveQueryData` methods (see [Occlusion queries](#occlusion-queries)). The bindings remain diagnostic because the forwarding behavior is not a console runtime oracle. Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 05d0259d7c..c629017fc7 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -157,6 +157,47 @@ void view_refs_leave_class(std::uint32_t slot, u64 resource, u64 counter, Retire constexpr std::uint32_t view_token_magic = 0x56573258; // "X2WV" +// X2W_D3D12_VIEW_TOKEN_GUARDED=1 (opt-in): note_view writes the token into title descriptor memory under an exception +// guard instead of asking first (commit_lazy, which takes xmem's commit mutex, then a VirtualQuery). A view is created +// about 10^5 times per second late in the load, by several recording threads at once. The destination is always in a +// registered descriptor range (title_backed), so the write normally does not fault; a lazily committed page is +// committed by xmem's handler on the first touch, as for any other write. +bool view_token_guarded() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_VIEW_TOKEN_GUARDED"); + return on; +} +LONG view_tokens_guarded_written, view_tokens_guarded_refused; +// Whether [dest, dest + bytes) lies inside one 4 KiB page. A descriptor heap's title backing has no alignment check, +// so a token can cross a page; such a token takes the full-span writable() check instead of the guarded write. +bool view_token_in_one_page(u64 dest, std::size_t bytes) +{ + return bytes && ((dest ^ (dest + bytes - 1)) & ~u64{0xFFF}) == 0; +} +// The token write of view_token_guarded(), for a span inside one page (view_token_in_one_page), so a refusal happens +// on the first byte and writes nothing. A page that refuses the write (no access, read-only, a guard page, an in-page +// error) leaves the descriptor without a token, as writable() returning false did; a guard page has its guard bit set +// again, on that page only. Between the fault that clears the guard bit and the re-arm, another thread's write to that +// page goes through, where writable() would have refused it. +__declspec(noinline) bool write_view_token(void* dest, const void* token, std::size_t bytes) noexcept +{ + DWORD code = 0; + __try { + std::memcpy(dest, token, bytes); + return true; + } __except (code = GetExceptionCode(), + code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_IN_PAGE_ERROR || code == STATUS_GUARD_PAGE_VIOLATION + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + if (code == STATUS_GUARD_PAGE_VIOLATION) { + MEMORY_BASIC_INFORMATION info{}; + DWORD old = 0; + if (VirtualQuery(dest, &info, sizeof(info)) && info.State == MEM_COMMIT) + VirtualProtect(dest, bytes, info.Protect | PAGE_GUARD, &old); + } + return false; + } +} + bool title_backed(u64 title_handle, u64 bytes) { bool inside = false; @@ -506,12 +547,16 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ } ReleaseSRWLockExclusive(¬e_lock); const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u; - if (dest_title != dest_desktop && title_backed(dest_title, token_bytes) && - x2w_local::writable(reinterpret_cast(dest_title), token_bytes)) { - std::uint32_t token[8] = {view_token_magic, record.id, static_cast(slot), 0, - static_cast(resource), static_cast(resource >> 32), 0, 0}; - std::memcpy(reinterpret_cast(dest_title), token, token_bytes); + const std::uint32_t token[8] = {view_token_magic, record.id, static_cast(slot), 0, + static_cast(resource), static_cast(resource >> 32), 0, 0}; + if (dest_title == dest_desktop || !title_backed(dest_title, token_bytes)) return; + if (view_token_guarded() && view_token_in_one_page(dest_title, token_bytes)) { + InterlockedIncrement(write_view_token(reinterpret_cast(dest_title), token, token_bytes) + ? &view_tokens_guarded_written : &view_tokens_guarded_refused); + return; } + if (x2w_local::writable(reinterpret_cast(dest_title), token_bytes)) + std::memcpy(reinterpret_cast(dest_title), token, token_bytes); } void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, UINT count, UINT increment) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index aa9f1ffa0c..4de8152233 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -6379,6 +6379,14 @@ extern "C" __declspec(dllexport) void x2w_d3d12_fail_view_allocations(int site, if (site >= 0 && site < view_allocation_sites) InterlockedExchange(&view_allocations_to_fail[site], count); } +// Fixture export (startup_view_token): view token writes made through the guard since the process started; both stay 0 +// without X2W_D3D12_VIEW_TOKEN_GUARDED=1. +extern "C" __declspec(dllexport) void x2w_d3d12_view_token_writes(LONG* written, LONG* refused) +{ + if (written) *written = view_tokens_guarded_written; + if (refused) *refused = view_tokens_guarded_refused; +} + // Fixture probe (startup_view_alloc): the sizes of the three view containers, the id + 1 that the tracked slot of a // title descriptor handle names (0: none), and whether a resource is still in the retire class. struct ViewStoreProbe { @@ -7422,6 +7430,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa for (int c = 0; c < x2w_local::null_cause_count; ++c) null_causes[c] = null_by_cause[c]; ReleaseSRWLockExclusive(&draw_lock); } + if (render_mode() && frame % 300 == 0 && view_token_guarded()) + log("x2w-render view tokens (X2W_D3D12_VIEW_TOKEN_GUARDED): written %ld, refused %ld", view_tokens_guarded_written, + view_tokens_guarded_refused); if (render_mode() && frame % 300 == 0 && root_srv_at_draw()) log("x2w-render root SRV copies (X2W_D3D12_ROOT_SRV_AT_DRAW): skipped %ld, copied %ld", root_srv_copies_skipped, root_srv_copies_made); diff --git a/tests/cmake/startup_view_token.cmake b/tests/cmake/startup_view_token.cmake new file mode 100644 index 0000000000..a173cef329 --- /dev/null +++ b/tests/cmake/startup_view_token.cmake @@ -0,0 +1,17 @@ +# The slot 18 view token in title descriptor memory, written after a check (unset) or under an exception guard +# (opt-in X2W_D3D12_VIEW_TOKEN_GUARDED=1): the same tokens, and no write to a read-only page or through a guard page. +add_executable(startup_view_token tests/startup_view_token.cpp) +target_compile_features(startup_view_token PRIVATE cxx_std_17) +target_link_libraries(startup_view_token PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS unset set) + set(token_test startup_view_token_${mode}_${backend}) + add_test(NAME ${token_test} COMMAND startup_view_token ${backend} ${mode}) + set(token_env "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + list(APPEND token_env "X2W_TRAP_LOG=${CMAKE_CURRENT_BINARY_DIR}/${token_test}.log") + if(mode STREQUAL "set") + list(APPEND token_env "X2W_D3D12_VIEW_TOKEN_GUARDED=1") + endif() + set_tests_properties(${token_test} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${token_env}") + endforeach() +endforeach() diff --git a/tests/startup_view_token.cpp b/tests/startup_view_token.cpp new file mode 100644 index 0000000000..302e81c708 --- /dev/null +++ b/tests/startup_view_token.cpp @@ -0,0 +1,219 @@ +// The view token note_view writes into title descriptor memory (X2W_D3D12_VIEW_TOKEN_GUARDED, d3d12_capture.inl). +// Three descriptor heaps over title memory the fixture owns, protected after creation: writable, read-only, and with a +// guard page. A texture SRV (device slot 18) goes into each, and a second one into the writable heap. In both modes the +// writable heap gets both tokens, the read-only heap stays zero without a crash, and the guard page keeps its guard bit +// and stays zero while the page after it stays read-write (the bit is set again on that page only). Two more heaps start 16 bytes before a page boundary (title backing has no alignment check), so +// their first descriptor's token crosses into a read-only or a guard page: in both modes the writable prefix keeps its +// bytes, the left page stays read-write without a guard bit, and the right page keeps its protection and stays zero. +// The stand-in's counters (x2w_d3d12_view_token_writes) tell the two paths apart: (0, 0) when the switch is unset, +// (2 written, 2 refused) when it is set; page-crossing tokens take the checked path and are not counted. +// +// startup_view_token +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_RENDER=1, plus X2W_D3D12_VIEW_TOKEN_GUARDED=1 for "set") +#include + +#include +#include +#include + +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_view_token_writes(LONG* written, LONG* refused); + +namespace { + +constexpr std::uint32_t token_magic = 0x56573258; // "X2WV" +constexpr UINT descriptors = 4; +constexpr SIZE_T region_bytes = 0x10000; +constexpr SIZE_T page = 0x1000; +constexpr SIZE_T prefix = 16; // bytes of a crossing heap's first descriptor on the left page +constexpr unsigned char sentinel = 0xA5; + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +int failures; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +DWORD protection(const void* address) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) ? info.Protect : 0; +} + +bool all_zero(const void* memory, std::size_t bytes) +{ + const auto* p = static_cast(memory); + for (std::size_t i = 0; i < bytes; ++i) + if (p[i]) return false; + return true; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (std::strcmp(argv[2], "unset") && std::strcmp(argv[2], "set"))) + return 2; + const bool guarded = std::strcmp(argv[2], "set") == 0; + std::setvbuf(stdout, nullptr, _IONBF, 0); + if (guarded != (GetEnvironmentVariableW(L"X2W_D3D12_VIEW_TOKEN_GUARDED", nullptr, 0) != 0)) { + std::puts("FAIL: X2W_D3D12_VIEW_TOKEN_GUARDED does not match the mode argument"); + return 2; + } + + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + DXGI_ADAPTER_DESC1 adapter_desc{}; + if (SUCCEEDED(adapter->GetDesc1(&adapter_desc))) std::printf("adapter=%ls\n", adapter_desc.Description); + ComPtr guest; + std::array parameters{}; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())))) + return 3; + const UINT stride = invoke(guest.Get(), 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!stride || UINT64{stride} * descriptors > 0x1000) return 3; + + // Title memory the fixture owns: one region per heap. The first three heaps start at their region's first page; the + // crossing heaps start `prefix` bytes before the region's second page. + enum { writable, read_only, guard, cross_read_only, cross_guard, heap_count }; + void* memory[heap_count]{}; + unsigned char* backing[heap_count]{}; + ComPtr heaps[heap_count]; + for (int i = 0; i < heap_count; ++i) { + memory[i] = VirtualAlloc(nullptr, region_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!memory[i]) return 3; + backing[i] = static_cast(memory[i]) + (i >= cross_read_only ? page - prefix : 0); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, descriptors}, reinterpret_cast(backing[i]), + UINT64{stride} * descriptors}; + if (FAILED(invoke(guest.Get(), 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heaps[i].GetAddressOf()))) return 3; + if (invoke(heaps[i].Get(), 9) != reinterpret_cast(backing[i])) { + std::puts("FAIL: the heap does not use the title memory it was given"); + return 3; + } + } + for (int i = cross_read_only; i < heap_count; ++i) std::memset(backing[i], sentinel, prefix); + DWORD old = 0; + if (!VirtualProtect(memory[read_only], page, PAGE_READONLY, &old) || + !VirtualProtect(memory[guard], page, PAGE_READWRITE | PAGE_GUARD, &old) || + !VirtualProtect(backing[cross_read_only] + prefix, page, PAGE_READONLY, &old) || + !VirtualProtect(backing[cross_guard] + prefix, page, PAGE_READWRITE | PAGE_GUARD, &old)) + return 3; + + D3D12_HEAP_PROPERTIES default_heap{}; + default_heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = texture.Height = 16; + texture.DepthOrArraySize = texture.MipLevels = 1; + texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture.SampleDesc.Count = 1; + ComPtr textures[2]; + const IID iid = __uuidof(ID3D12Resource); + for (auto& t : textures) + if (FAILED(invoke(guest.Get(), 27, &default_heap, D3D12_HEAP_FLAG_NONE, &texture, D3D12_RESOURCE_STATE_COMMON, + static_cast(nullptr), &iid, + reinterpret_cast(t.GetAddressOf())))) + return 3; + // Every byte of the description identifies the view, so it is zeroed before its fields are set. + D3D12_SHADER_RESOURCE_VIEW_DESC srv; + std::memset(&srv, 0, sizeof(srv)); + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + const auto view = [&](int texture_index, void* base, UINT index) { + invoke(guest.Get(), 18, static_cast(textures[texture_index].Get()), &srv, + reinterpret_cast(base) + UINT64{stride} * index); + }; + view(0, memory[writable], 0); + view(0, memory[read_only], 0); + view(1, memory[guard], 0); + view(1, memory[writable], 1); + view(0, backing[cross_read_only], 0); + view(1, backing[cross_guard], 0); + + const auto* words = static_cast(memory[writable]); + expect(words[0] == token_magic && words[2] == 18, "the writable heap's first descriptor holds no slot 18 token"); + const auto* second = reinterpret_cast(static_cast(memory[writable]) + stride); + expect(second[0] == token_magic && second[1] != words[1], "the writable heap's second descriptor holds no new token"); + expect(all_zero(memory[read_only], UINT64{stride} * descriptors), "the read-only heap was written"); + MEMORY_BASIC_INFORMATION info{}; + expect(VirtualQuery(memory[guard], &info, sizeof(info)) && (info.Protect & PAGE_GUARD), + "the guard page lost its guard bit"); + // The guard bit is set again on the guard page only: the rest of the region stays read-write. + expect(protection(static_cast(memory[guard]) + page) == PAGE_READWRITE, + "the page after the guard page changed its protection"); + if (VirtualProtect(memory[guard], page, PAGE_READWRITE, &old)) + expect(all_zero(memory[guard], UINT64{stride} * descriptors), "the guard page was written"); + + // The crossing tokens: nothing written on either side, and neither page's protection changed. + for (int i = cross_read_only; i < heap_count; ++i) { + const char* const name = i == cross_read_only ? "read-only" : "guard"; + const DWORD left = protection(backing[i]), right = protection(backing[i] + prefix); + std::printf("crossing heap (%s right page): left page 0x%lx, right page 0x%lx\n", name, left, right); + bool prefix_kept = true; + for (SIZE_T b = 0; b < prefix; ++b) prefix_kept = prefix_kept && backing[i][b] == sentinel; + expect(prefix_kept, "a crossing heap's writable prefix changed"); + expect(left == PAGE_READWRITE, "a crossing heap's left page changed its protection"); + expect(right == (i == cross_read_only ? PAGE_READONLY : (PAGE_READWRITE | PAGE_GUARD)), + "a crossing heap's right page changed its protection"); + if (VirtualProtect(backing[i] + prefix, page, PAGE_READWRITE, &old)) + expect(all_zero(backing[i] + prefix, UINT64{stride} * descriptors - prefix), + "a crossing heap was written on its right page"); + } + + LONG written = -1, refused = -1; + x2w_d3d12_view_token_writes(&written, &refused); + std::printf("view tokens through the guard: written %ld, refused %ld\n", written, refused); + if (guarded) + expect(written == 2 && refused == 2, "the guarded path did not write 2 tokens and refuse 2"); + else + expect(written == 0 && refused == 0, "the guarded path ran with the switch unset"); + if (failures) return 1; + std::printf("PASS (%s): writable heap 2 tokens, read-only heap untouched, guard page kept, crossing tokens " + "refused without a write or a protection change\n", argv[2]); + return 0; +}