diff --git a/CMakeLists.txt b/CMakeLists.txt index a5b4d5e5d5..3fe42cdf4f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -281,6 +281,9 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME xmem_physical_write_owner COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xmem_physical_write_owner_check.py" "$") set_tests_properties(xmem_physical_write_owner PROPERTIES TIMEOUT 120) + # 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" "$") @@ -1480,6 +1483,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 2b012ca84d..52b6943183 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2004,6 +2004,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; @@ -2114,7 +2142,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 57663f42ab..82e54e3789 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -553,8 +553,9 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC unreadable = false; const auto bytes = address_texture_bytes(device, desc); // The transient upload ring accepts individual copies up to 64 MiB. - if (bytes > x2w_startup::max_published_texture_bytes) return nullptr; - unreadable = !x2w_local::readable(reinterpret_cast(address), bytes); + if (bytes > x2w_startup::max_published_texture_bytes || !bytes || address < 0x10000) return nullptr; + // Pages can be mapped between two publication attempts in the same frame. + unreadable = readable_window(address, static_cast(bytes)) != bytes; if (unreadable) return nullptr; std::lock_guard lock(tiled_srv_mutex); const auto [first, last] = tiled_srv_addresses.equal_range(address); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0a3ddf5832..d6132f3c9e 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -611,10 +611,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]); @@ -1024,9 +1025,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) @@ -3461,9 +3467,38 @@ D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(Wrapper* list, u64 title_address, st return ring_copy(list, title_address, bytes, &offset, &resource) && resource ? resource->GetGPUVirtualAddress() + offset : 0; } -// 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); } @@ -5903,7 +5938,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) { @@ -5916,7 +5951,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, @@ -9050,6 +9089,8 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa char line[640]; if (view_census_line(line, sizeof(line))) log("%s", line); } + 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 a95f40fbea..f7a9492093 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -66,6 +66,9 @@ struct PhysicalMemory { ULONG64 stamp = 0; }; std::map runs; + // 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}; @@ -1072,6 +1075,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 { @@ -2276,6 +2283,40 @@ const int file_io_wrapped = [] { }(); } // 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. A token that names diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 5ff7b8500d..6460be79f4 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -27,3 +27,4 @@ EXPORTS x2w_xmem_map_counts @25 x2w_xmem_stable_call @26 x2w_xmem_alias_counts @27 + x2w_xmem_mapped_bytes @28 diff --git a/tests/startup_memory_srv_diag.cpp b/tests/startup_memory_srv_diag.cpp index ff90989f53..0a5c56b5fc 100644 --- a/tests/startup_memory_srv_diag.cpp +++ b/tests/startup_memory_srv_diag.cpp @@ -141,7 +141,7 @@ int draw_memory_srv_diagnostics(ID3D12Device* desktop, void* guest, void* list) } const bool removed = handler && RemoveVectoredExceptionHandler(handler); reserved_texel_address = 0; - VirtualFree(reserved, 0, MEM_RELEASE); + if (!removed) return 57; // A logged refusal faults in publish_tiled_texture's probe and the 1-byte probe in // log_refused_memory_srv. Main had three faults because the reason function probed again. @@ -157,6 +157,13 @@ int draw_memory_srv_diagnostics(ID3D12Device* desktop, void* guest, void* list) std::fprintf(stderr, "Expected two texture_unreadable refusals and their shape:\n%s", report.data()); return 59; } + // Map and retry in the same frame, then read the new descriptor through a draw. + void* const backing = VirtualAlloc(reserved, 4096, MEM_COMMIT, PAGE_READWRITE); + if (backing != reserved) return 60; + const std::array expected{73, 0, 0, 255}; + std::memcpy(backing, expected.data(), expected.size()); + invoke(guest, 70, ptr(&texel), ptr(&unreadable), cpu); + draw(2); } return 0; } diff --git a/tests/startup_memory_srv_diag_check.py b/tests/startup_memory_srv_diag_check.py index fa7a6828da..e70de17081 100644 --- a/tests/startup_memory_srv_diag_check.py +++ b/tests/startup_memory_srv_diag_check.py @@ -73,6 +73,12 @@ def check(directory, consumer, backend, control=False): if right != bytes((23 + 32 * (y % 2), 0, 0, 255)): raise AssertionError(f"column 1 row {y}: {right.hex()}, expected the R8 texel") + for y in (0, 2): + offset = (y * 8 + 2) * 4 + retry = pixels[offset:offset + 4] + if retry != bytes((73, 0, 0, 255)): + raise AssertionError(f"column 2 row {y}: {retry.hex()}, expected the texel mapped in the same frame") + lines = census_block(result.stdout) if len(lines) < 4: raise AssertionError("census report has fewer than four lines:\n" + "\n".join(lines)) 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..9158763ca5 --- /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])