From c0e5f06d988b50086d9381937da2c15a54b389c6 Mon Sep 17 00:00:00 2001 From: Its3rr0rsWRLD <92172873+Its3rr0rsWRLD@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:52:11 -0600 Subject: [PATCH] startup: stop probing unmapped guest memory from the texture and no-op paths Every readability probe that touches an unmapped page raises a first-chance access violation. Under the debug launcher each one stops the process for a debugger round trip. On the title tested there were about 21000-25000 of them per run, almost all before the intro: by-address (slot-70) textures whose pages were not mapped yet, and a queue no-op slot (31) called every frame with the base of a physical-page pool whose mapping had failed. Slot 31 is now handled by queue_page_mappings (#2307); the shape-check cap below still covers the slots left to queue_dynamic. No intended behaviour change: the same addresses are found readable or unreadable as before; only how that is found changes. The one timing difference is the 30-frame retry interval for by-address texture addresses found unmapped (below). - xmem: new export x2w_xmem_mapped_bytes(address, bytes, &mapped) answers from the page registry, without touching memory, how many bytes from address are mapped. It answers only inside xmem's page-mapping reservations; for any other address, a range past the reservation, a range a commit at address may cover, or an unmapped answer Windows does not confirm as reserved, it gives no answer and the caller probes as before. - d3d12_xs: readable_window asks xmem first (unmapped: no touch; mapped prefix: probed as before). publish_tiled_texture, names_known_iid, hex_text and the ExecuteCommandLists shape test in queue_dynamic go through readable_window instead of x2w_local::readable. - A by-address texture address that a probe found unmapped is not probed again for 30 frames (unless a write to it is announced). - queue_dynamic checks only the first 32 calls of a slot for an IID, like noop_slot and device_noop_slot already do. - The 5 s report logs "x2w-d3d12 readability: unmapped by xmem's page registry N, unreadable probes skipped N". - xmem_shim.def: x2w_xmem_mapped_bytes is ordinal 23 (17-22 are taken on main). - Tests: xmem_mapped_bytes (the export's answers), startup_queue_probe_{reserved,xmem}_{warp,hardware} (200 calls of unknown queue slot 30 with a reserved, unmapped r9: at most 32 faults without xmem, 0 with it). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01X1EBSe6YfE2ivQChRsx1hc --- CMakeLists.txt | 15 +++ src/startup_stubs/d3d12_draw.inl | 38 +++++++- src/startup_stubs/d3d12_memory_srv.inl | 14 ++- src/startup_stubs/d3d12_xs_device.cpp | 52 +++++++++- src/xmem_mapped_pages.cpp | 41 ++++++++ src/xmem_shim.def | 1 + tests/startup_queue_probe.cpp | 128 +++++++++++++++++++++++++ tests/xmem_mapped_bytes_check.py | 67 +++++++++++++ 8 files changed, 349 insertions(+), 7 deletions(-) create mode 100644 tests/startup_queue_probe.cpp create mode 100644 tests/xmem_mapped_bytes_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index cffb43f70a..45a899236a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -236,6 +236,9 @@ if(EXISTS "${INTAKE_PYTHON}") # and section count the DirectStorage heartbeat reports from it. add_test(NAME xmem_page_stats COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xmem_page_stats_check.py" "$") + # Readability checks ask the page registry instead of touching unmapped pages. + add_test(NAME xmem_mapped_bytes COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/xmem_mapped_bytes_check.py" "$") # A few mapped pages commit about those pages, not the whole 256 MiB slab that holds them (#1199). add_test(NAME xmem_mapped_pages_commit COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xmem_mapped_pages_commit_check.py" "$") @@ -1245,6 +1248,18 @@ set_tests_properties(startup_queue_page_batch_warp PROPERTIES RUN_SERIAL TRUE TI set_tests_properties(startup_queue_page_batch_runs_warp PROPERTIES RUN_SERIAL TRUE TIMEOUT 90 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=1") +# Unknown queue slots do not fault on every call for a reserved, unmapped argument address. +add_executable(startup_queue_probe tests/startup_queue_probe.cpp) +target_compile_features(startup_queue_probe PRIVATE cxx_std_17) +target_link_libraries(startup_queue_probe PRIVATE d3d12_xs_shim d3d12 dxgi) +add_dependencies(startup_queue_probe xmem_shim) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_queue_probe_reserved_${backend} COMMAND startup_queue_probe ${backend} reserved) + add_test(NAME startup_queue_probe_xmem_${backend} COMMAND startup_queue_probe ${backend} xmem "$") + set_tests_properties(startup_queue_probe_reserved_${backend} startup_queue_probe_xmem_${backend} PROPERTIES + TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1") +endforeach() + # Closed lists stay submittable, also after their allocator's Reset (#1352). add_executable(startup_list_resubmit tests/startup_list_resubmit.cpp) target_compile_features(startup_list_resubmit PRIVATE cxx_std_17) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 57cef51302..dfd3834f69 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1152,6 +1152,34 @@ void buffer_view(D3D12_CPU_DESCRIPTOR_HANDLE dest, ID3D12Resource* buffer, u64 o // Recheck single-mip R8 and A8 planes on their first bind each frame and other textures every 15 frames. // Targets and UAVs are GPU-written and never uploaded. LONG textures_uploaded, texture_bytes_uploaded, textures_unreadable; + +// Texel addresses of by-address textures whose first page a probe found unreadable, with the frame of +// the probe. Outside xmem's page reservations the probe touches one byte per page, and an unmapped page +// costs a first-chance access violation (under the debug launcher one debugger round trip each). Such an +// address is not probed again for unreadable_retry_frames frames; after that it is, since the title maps +// its pages while it loads. +constexpr LONG unreadable_retry_frames = 30; +std::mutex unreadable_mutex; +std::unordered_map unreadable_addresses; +LONG address_probe_skipped; + +bool recently_unreadable(u64 address) +{ + const std::lock_guard guard(unreadable_mutex); + const auto it = unreadable_addresses.find(address); + if (it == unreadable_addresses.end()) return false; + if (frame_number - it->second <= unreadable_retry_frames) return true; + unreadable_addresses.erase(it); + return false; +} + +void note_unreadable(u64 address) +{ + const std::lock_guard guard(unreadable_mutex); + if (unreadable_addresses.size() > 65536) unreadable_addresses.clear(); + unreadable_addresses[address] = frame_number; +} + u64 hash_memory(const unsigned char* data, std::size_t bytes) { u64 h = 0xcbf29ce484222325ull; @@ -1255,7 +1283,15 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) : x2w_startup::recheck_cpu_texture(desc, total, elapsed)); const bool reusable = state.done && (!state.pending_list || state.pending_list == list); if (reusable && !announced && !recheck) return true; - if (readable_window(reinterpret_cast(memory), static_cast(total)) < total) { + // An address a probe found unmapped is not probed again for 30 frames, unless a write was announced. + bool skipped_probe = false; + if (tiled_address && !announced && recently_unreadable(reinterpret_cast(memory))) { + skipped_probe = true; + InterlockedIncrement(&address_probe_skipped); + } + std::size_t window = 0; + if (skipped_probe || (window = readable_window(reinterpret_cast(memory), static_cast(total))) < total) { + if (tiled_address && !skipped_probe && !window) note_unreadable(reinterpret_cast(memory)); if (!state.done) InterlockedIncrement(&textures_unreadable); if (console) return false; state.done = true; diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index b441d44014..9fe7b4f9d4 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -346,7 +346,19 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC { const auto bytes = address_texture_bytes(device, desc); // The transient upload ring accepts individual copies up to 64 MiB. - if (bytes > (64ull << 20) || !x2w_local::readable(reinterpret_cast(address), bytes)) return nullptr; + if (bytes > (64ull << 20) || !bytes || address < 0x10000) return nullptr; + // The texels must be readable. The test goes through xmem's page registry (readable_window), so an + // unmapped page inside a title page reservation is not touched; an address found unmapped is not + // probed again for 30 frames (recently_unreadable). + if (recently_unreadable(address)) { + InterlockedIncrement(&address_probe_skipped); + return nullptr; + } + const std::size_t readable_bytes = readable_window(address, static_cast(bytes)); + if (readable_bytes != bytes) { + if (!readable_bytes) note_unreadable(address); + return nullptr; + } std::lock_guard lock(tiled_srv_mutex); const auto [first, last] = tiled_srv_addresses.equal_range(address); for (auto it = first; it != last; ++it) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0c2a5caae3..7a2d0de57b 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -33,6 +33,7 @@ #include "startup_stubs/address_texture.h" #include "startup_stubs/list_upload_pages.h" #include "startup_stubs/resource_budget.h" +#include #include #include "startup_stubs/derived_blend.h" #include "startup_stubs/placement_publish.h" @@ -374,10 +375,11 @@ void guid_text(const GUID* g, char* out, std::size_t size) g->Data4[7]); } +std::size_t readable_window(u64 address, std::size_t wanted); void hex_text(const void* data, std::size_t bytes, char* out, std::size_t size) { out[0] = 0; - if (!data || !x2w_local::readable(data, bytes)) return; + if (!data || readable_window(reinterpret_cast(data), bytes) < bytes) return; const auto* p = static_cast(data); std::size_t used = 0; for (std::size_t i = 0; i < bytes && used + 4 < size; ++i) used += std::snprintf(out + used, size - used, "%02x ", p[i]); @@ -522,9 +524,14 @@ void fill_all_traps(std::index_sequence) // A call that passes a known interface IID is a creation or query call: a no-op that returned 0 // would hand the title "success" with no object. Such calls trap instead of being ignored. +// The readability test goes through xmem's page registry first (readable_window): a value that is an +// address inside a title page reservation with nothing mapped there, such as the base of a physical-page +// pool whose mapping failed, is answered without touching it. Probing it cost one first-chance access +// violation per call (423 for one such pool base passed to queue slot 31 in one run, before slot 31 was +// mapped to queue_page_mappings). bool names_known_iid(u64 value) { - if (value < 0x10000 || !x2w_local::readable(reinterpret_cast(value), sizeof(GUID))) return false; + if (value < 0x10000 || readable_window(value, sizeof(GUID)) < sizeof(GUID)) return false; return kind_for(*reinterpret_cast(value)) != other_kind; } bool create_shaped(u64 a, u64 b, u64 c, u64 d, u64 e, u64 f, u64 g) @@ -2268,9 +2275,38 @@ bool ring_copy(u64 title_address, std::size_t bytes, u64* offset) return true; } -// Number of contiguous readable bytes at address, up to wanted. +// xmem's page registry (x2w_xmem_mapped_bytes) answers for addresses in the title's mapped-page +// reservations without touching them. Probing an unmapped page there costs a first-chance access +// violation each, and under the debug launcher a debugger round trip each (about 21000 in one +// loading screen, almost all from by-address textures whose pages were not mapped yet). +using XmemMappedBytes = BOOL(WINAPI*)(ULONG_PTR, SIZE_T, SIZE_T*); +XmemMappedBytes xmem_mapped_bytes() noexcept +{ + static std::atomic found{nullptr}; + static std::atomic lookups{0}; + if (const auto f = found.load(std::memory_order_acquire)) return f; + if (lookups.fetch_add(1, std::memory_order_relaxed) >= 256) return nullptr; // xmem.dll not loaded or an older one + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + const auto f = xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_mapped_bytes")) : nullptr; + if (f) found.store(f, std::memory_order_release); + return f; +} +LONG xmem_answered_unmapped; + +// Number of contiguous readable bytes at address, up to wanted. Where xmem knows the pages, only its +// mapped prefix is touched (no fault in the common case); elsewhere one byte per page is touched. std::size_t readable_window(u64 address, std::size_t wanted) { + if (const auto query = wanted ? xmem_mapped_bytes() : nullptr) { + SIZE_T mapped = 0; + if (query(static_cast(address), wanted, &mapped)) { + if (!mapped) { + InterlockedIncrement(&xmem_answered_unmapped); + return 0; + } + return x2w_local::probe_readable(static_cast(address), mapped); + } + } return x2w_local::probe_readable(static_cast(address), wanted); } @@ -3633,7 +3669,7 @@ __declspec(noinline) u64 queue_dynamic(Wrapper* self, u64 rdx, u64 r8, u64 r9) static_cast(hr)); return static_cast(hr); } - if (rdx >= 1 && rdx <= 64 && r8 >= 0x10000 && x2w_local::readable(reinterpret_cast(r8), rdx * sizeof(void*))) { + if (rdx >= 1 && rdx <= 64 && r8 >= 0x10000 && readable_window(r8, rdx * sizeof(void*)) >= rdx * sizeof(void*)) { auto* const* lists = reinterpret_cast(r8); bool all_lists = true; for (u64 i = 0; i < rdx; ++i) { @@ -3646,7 +3682,11 @@ __declspec(noinline) u64 queue_dynamic(Wrapper* self, u64 rdx, u64 r8, u64 r9) return 0; } } - if (create_shaped(rdx, r8, r9, 0, 0, 0, 0)) { + // As in noop_slot, only the first calls of a slot are checked for an IID: the check reads its + // arguments, and an unchecked slot called every frame with a pointer-shaped non-pointer (slot 31's + // r9, before slot 31 was mapped to queue_page_mappings) paid a first-chance access violation per call. + static LONG shape_checks; + if (shape_checks < 32 && InterlockedIncrement(&shape_checks) <= 32 && create_shaped(rdx, r8, r9, 0, 0, 0, 0)) { char name[64]; std::snprintf(name, sizeof(name), "CommandQueue::slot%d(passes an IID)", N); x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, name, N & 0xFF, reinterpret_cast(self), rdx, r8, r9, @@ -5434,6 +5474,8 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa "(region-information proofs %lld, region queries %lld)", views_noted, views_distinct, descriptors_copied, static_cast(heap_infos().size()), static_cast(placed_buffer_calls), static_cast(placed_buffer_region_info), static_cast(placed_buffer_queries)); + log("x2w-d3d12 readability: unmapped by xmem's page registry %ld, unreadable probes skipped %ld", + InterlockedCompareExchange(&xmem_answered_unmapped, 0, 0), InterlockedCompareExchange(&address_probe_skipped, 0, 0)); { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 7567418981..541d15fc2c 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -57,6 +57,9 @@ struct PhysicalMemory { SIZE_T mirror_bytes = 0; std::set explicit_mirror_pages; std::map runs; // OS views: base -> bytes + // Ordinary commits the caller placed at an address (XMemVirtualAlloc "commit at address"): memory that + // x2w_xmem_mapped_bytes cannot judge from the page registry. + std::map commits; // The slabs and their 64 KiB slots; released slots are reused lowest first, so that pages reused together // are adjacent slots again. x2w_xmem::SlabSlots slots{era_physical::page_bytes}; @@ -853,6 +856,10 @@ void* local_virtual_alloc(void* address, SIZE_T bytes, DWORD type, ULONGLONG att result = VirtualAlloc2(GetCurrentProcess(), address, bytes, MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, protect, nullptr, 0); } + if (result) { + const std::lock_guard guard(memory.mutex); + memory.commits.insert_or_assign(reinterpret_cast(result), bytes); + } how = "commit at address"; } } else { @@ -1626,6 +1633,40 @@ const bool lazy_commit_installed = [] { }(); } // namespace +// Experimental export: whether [address, address + bytes) is mapped, answered from the page registry +// without touching the memory. A probe that touches an unmapped page costs one first-chance access +// violation (under the debug launcher, one debugger round trip each). Answers only for addresses inside +// a placeholder reservation that pages are mapped into (the reservations recorded for page mapping): +// *mapped receives the number of bytes from address on whose 64 KiB pages have a view, up to bytes. +// Returns FALSE (no answer; the caller probes instead) for any other address, for one that a commit at +// address may cover, for a range that runs past its reservation, and for an unmapped answer that Windows +// does not confirm (a released reservation the registry still names). +extern "C" BOOL WINAPI x2w_xmem_mapped_bytes(ULONG_PTR address, SIZE_T bytes, SIZE_T* mapped) +{ + if (!mapped || !bytes || address > std::numeric_limits::max() - bytes) return FALSE; + const ULONG_PTR end = address + bytes; + ULONG_PTR at = address & ~(ULONG_PTR{page_bytes} - 1); + { + const std::lock_guard guard(memory.mutex); + const auto reservation = owned_reservation(address); + if (reservation == memory.reservations.end()) return FALSE; + const ULONG_PTR reservation_end = reservation->first + reservation->second; + if (end > reservation_end) return FALSE; + if (!memory.commits.empty()) { + auto commit = memory.commits.lower_bound(end); + if (commit != memory.commits.begin() && std::prev(commit)->first + std::prev(commit)->second > address) return FALSE; + } + while (at < end && memory.views.count(at)) at += page_bytes; + } + *mapped = at <= address ? 0 : static_cast((at < end ? at : end) - address); + if (*mapped == 0) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) || info.State != MEM_RESERVE) + return FALSE; + } + return TRUE; +} + // Experimental export: writes bytes into physical pages named by the title's // page tokens (page number << 4, as XMemMapPhysicalPages takes them), starting offset bytes into the // first page. DirectStorage requests can name such pages as their destination. diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 3776c7529f..0a27bc0d46 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -22,3 +22,4 @@ EXPORTS x2w_xmem_release_section @20 x2w_xmem_match_section @21 X2WMapPageBatch @22 + x2w_xmem_mapped_bytes @23 diff --git a/tests/startup_queue_probe.cpp b/tests/startup_queue_probe.cpp new file mode 100644 index 0000000000..909633b302 --- /dev/null +++ b/tests/startup_queue_probe.cpp @@ -0,0 +1,128 @@ +// Unknown console queue slots must not fault on every call (startup_queue_probe). +// +// startup_queue_probe reserved +// startup_queue_probe xmem +// +// The title called queue slot 31 every frame with r9 = the base of a physical-page pool whose mapping +// had failed: reserved memory with nothing behind it. Slot 31 now maps pages (queue_page_mappings), but +// any slot still left to the shape dispatch (queue_dynamic) checks pointer-shaped arguments for an IID, +// and the check touched them on every call: one first-chance access violation per call (423 in one run +// at d3d12_xs probe_readable). This test calls slot 30, which has no known meaning, the same way. +// +// reserved: the address is a plain VirtualAlloc reservation (unknown to xmem). 200 calls may fault at +// most 32 times (the first calls of a slot are still checked by probing). +// xmem: the xmem shim is loaded as xmem.dll and the address is an XMemVirtualAlloc reservation with +// no pages mapped. xmem's page registry answers for it, so 200 calls fault 0 times. +// +// Every call must return 0 (the slot stays a no-op). A vectored handler counts access violations at the +// address; it lets them continue to the stand-in's own handler. +// Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. +#include +#include +#include + +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d); +} + +volatile std::uintptr_t watched_base, watched_end; +volatile LONG faults; +LONG CALLBACK count_faults(EXCEPTION_POINTERS* e) +{ + const EXCEPTION_RECORD* r = e->ExceptionRecord; + if (r->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r->NumberParameters >= 2 && + r->ExceptionInformation[1] >= watched_base && r->ExceptionInformation[1] < watched_end) + InterlockedIncrement(&faults); + return EXCEPTION_CONTINUE_SEARCH; +} + +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONG64, DWORD); +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 3) return 2; + const bool use_xmem = std::strcmp(argv[2], "xmem") == 0; + if (!use_xmem && std::strcmp(argv[2], "reserved") != 0) return 2; + if (use_xmem && argc < 4) return 2; + XMemVirtualAllocFn xmem_reserve = nullptr; + if (use_xmem) { + SetEnvironmentVariableW(L"X2W_XMEM_PERMISSIVE", L"1"); + const HMODULE xmem = LoadLibraryA(argv[3]); + if (!xmem || GetModuleHandleW(L"xmem.dll") != xmem) { + std::fprintf(stderr, "cannot load %s as xmem.dll\n", argv[3]); + return 20; + } + xmem_reserve = reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")); + if (!xmem_reserve || !GetProcAddress(xmem, "x2w_xmem_mapped_bytes")) return 21; + } + + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + + std::array parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 4; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + void* queue = nullptr; + if (FAILED(static_cast(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))))) + return 5; + + constexpr SIZE_T bytes = 16 * 0x10000; + void* base = use_xmem ? xmem_reserve(nullptr, bytes, 0x20402000, 0x23, PAGE_READWRITE) + : VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS); + if (!base) return 6; + watched_base = reinterpret_cast(base); + watched_end = watched_base + bytes; + void* handler = AddVectoredExceptionHandler(1, count_faults); + if (!handler) return 7; + + // The title's shape: a small count, a stack array, then the pool base. + std::array batch{0x2, 0x200000003, 0x300000000, 0x2, 0x200000003, 0x300000000}; + constexpr int calls = 200; + constexpr unsigned unknown_slot = 30; + for (int i = 0; i < calls; ++i) { + const Word result = invoke(queue, unknown_slot, 1 + (i & 1) * 2, arg(batch.data()), arg(base)); + if (result != 0) { + std::printf("call %d returned 0x%llx\n", i, static_cast(result)); + return 8; + } + } + RemoveVectoredExceptionHandler(handler); + const LONG seen = faults; + const LONG allowed = use_xmem ? 0 : 32; + std::printf("%s: %d calls of queue slot %u with r9=%p -> %ld access violations at the address (allowed %ld)\n", + use_xmem ? "xmem" : "reserved", calls, unknown_slot, base, seen, allowed); + return seen <= allowed ? 0 : 9; +} diff --git a/tests/xmem_mapped_bytes_check.py b/tests/xmem_mapped_bytes_check.py new file mode 100644 index 0000000000..2951f1dec2 --- /dev/null +++ b/tests/xmem_mapped_bytes_check.py @@ -0,0 +1,67 @@ +"""x2w_xmem_mapped_bytes answers from the page registry, without touching memory, inside xmem's reservations.""" +import ctypes as C +from pathlib import Path +import sys + +PAGE_BYTES = 65536 +WIN_RESERVE, WIN_COMMIT, WIN_RELEASE = 0x2000, 0x1000, 0x8000 +NOACCESS, READWRITE = 1, 4 + + +def bind(library, name, args, result): + function = getattr(library, name) + function.argtypes, function.restype = args, result + return function + + +def main(path): + kernel = C.WinDLL("kernel32.dll", use_last_error=True) + kernel.SetEnvironmentVariableW.argtypes = [C.c_wchar_p, C.c_wchar_p] + assert kernel.SetEnvironmentVariableW("X2W_XMEM_PERMISSIVE", "1") + library = C.WinDLL(str(Path(path).resolve()), use_last_error=True, winmode=0x900) + pointer, number, dword = C.c_void_p, C.c_size_t, C.c_ulong + mapped_bytes = bind(library, "x2w_xmem_mapped_bytes", [number, number, C.POINTER(number)], C.c_int) + virtual_alloc = bind(library, "XMemVirtualAlloc", [pointer, number, dword, C.c_ulonglong, dword], pointer) + allocate = bind(library, "XMemAllocatePhysicalPages", [number, C.POINTER(number), C.POINTER(number)], C.c_int) + release = bind(library, "XMemFreePhysicalPages", [number, C.POINTER(number)], C.c_int) + contiguous = bind(library, "XMemMapPhysicalPages", [pointer, number, C.POINTER(number)], pointer) + free = bind(C.WinDLL("kernelbase.dll", use_last_error=True), "VirtualFree", [pointer, number, dword], C.c_int) + + def query(address, size): + value = number(12345) + answered = mapped_bytes(address, size, C.byref(value)) + return value.value if answered else None + + # Outside every reservation xmem has no answer: the caller probes. + outside = (C.c_char * 16)() + assert query(C.addressof(outside), 16) is None, "answered for ordinary process memory" + assert not mapped_bytes(C.addressof(outside), 16, None), "accepted a null result" + + base = virtual_alloc(None, 4 * PAGE_BYTES, WIN_RESERVE, 0, NOACCESS) + assert base, C.get_last_error() + count, pages = number(2), (number * 2)() + assert allocate(0x280, C.byref(count), pages) and count.value == 2 + try: + assert query(base, PAGE_BYTES) == 0, "an unmapped reservation page was not reported unmapped" + assert query(base + 0x1000, 0x2000) == 0 + # Pages 1 and 2 mapped: page 0 is still unmapped, a range from page 1 is mapped through page 2. + tokens = (number * 2)(pages[0], pages[1]) + assert contiguous(base + PAGE_BYTES, 2, tokens) == base + PAGE_BYTES, C.get_last_error() + assert query(base, 3 * PAGE_BYTES) == 0, "a range whose first page is unmapped was reported mapped" + assert query(base + PAGE_BYTES + 0x10, 0x100) == 0x100 + assert query(base + PAGE_BYTES + 0x10, 3 * PAGE_BYTES - 0x10) == 2 * PAGE_BYTES - 0x10, "mapped prefix" + C.memmove(base + PAGE_BYTES, b"mapped", 6) # the mapped prefix is really there + # A range past the end of the reservation has no answer. + assert query(base + 3 * PAGE_BYTES, 2 * PAGE_BYTES) is None, "answered past the reservation" + assert contiguous(base + PAGE_BYTES, 2, None) == base + PAGE_BYTES + assert query(base + PAGE_BYTES, PAGE_BYTES) == 0, "an unmapped page was still reported mapped" + finally: + release(2, pages) + free(base, 0, WIN_RELEASE) + # Released: Windows no longer shows a reservation, so the registry's stale entry gives no answer. + assert query(base, PAGE_BYTES) is None, "answered for a released reservation" + print("mapped bytes: outside=no answer, unmapped=0, mapped prefix=0x1fff0, past the end=no answer, released=no answer") + + +if __name__ == "__main__": + main(sys.argv[1])