From 7ccdb7a47182cdb51c9629519a692b6ba498259c Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 09:00:04 +0800 Subject: [PATCH 001/775] Test graphics pipeline stream draws through a root SRV --- CMakeLists.txt | 12 ++++ docs/experiments.md | 9 +++ tests/desktop_gpu.h | 1 + tests/offscreen_check.cpp | 7 ++ tests/stream_root_srv.cpp | 135 +++++++++++++++++++++++++++++++++++++ tests/stream_root_srv.hlsl | 20 ++++++ 6 files changed, 184 insertions(+) create mode 100644 tests/stream_root_srv.cpp create mode 100644 tests/stream_root_srv.hlsl diff --git a/CMakeLists.txt b/CMakeLists.txt index dc56555eb..aec0d8ad5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -267,6 +267,16 @@ add_custom_command(OUTPUT "${pixel_vs_linear}" COMMAND "${DXC_EXECUTABLE}" -T vs target_sources(offscreen_check PRIVATE tests/pixel_aot_render.cpp tests/pixel_compare_render.cpp "${pixel_vs}" "${pixel_vs_linear}") target_sources(offscreen_check PRIVATE tests/desktop_gpu.cpp tests/mesh_entry_draw.cpp tests/mesh_shadow_draw.cpp) +target_sources(offscreen_check PRIVATE tests/stream_root_srv.cpp) +foreach(stage IN ITEMS vs ps) + string(TOUPPER "${stage}" entry) + set(header "${CMAKE_CURRENT_BINARY_DIR}/stream_root_srv_${stage}.h") + add_custom_command(OUTPUT "${header}" + COMMAND "${DXC_EXECUTABLE}" -T ${stage}_6_0 -E ${entry}Main -Vn stream_root_srv_${stage} + -Fh "${header}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/stream_root_srv.hlsl" + DEPENDS tests/stream_root_srv.hlsl VERBATIM) + target_sources(offscreen_check PRIVATE "${header}") +endforeach() set(descriptor_window_cs "${CMAKE_CURRENT_BINARY_DIR}/descriptor_window_submissions_cs.h") add_custom_command(OUTPUT "${descriptor_window_cs}" COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E main -Vn descriptor_window_submissions_cs -Fh "${descriptor_window_cs}" @@ -536,6 +546,8 @@ foreach(adapter IN ITEMS hardware warp) add_test(NAME ffx_device_init_${adapter} COMMAND offscreen_check ${adapter} --ffx-device-init) add_test(NAME ffx_recurrent_${adapter} COMMAND offscreen_check ${adapter} --ffx-recurrent) add_test(NAME dual_uav_${adapter} COMMAND offscreen_check ${adapter} --dual-uav) + add_test(NAME stream_root_srv_${adapter} COMMAND offscreen_check ${adapter} --stream-root-srv) + set_tests_properties(stream_root_srv_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) add_test(NAME descriptor_window_submissions_${adapter} COMMAND offscreen_check ${adapter} --descriptor-window-submissions) add_test(NAME descriptor_window_stale_${adapter} COMMAND offscreen_check ${adapter} --descriptor-window-stale) set_tests_properties(descriptor_window_submissions_${adapter} descriptor_window_stale_${adapter} diff --git a/docs/experiments.md b/docs/experiments.md index 49148965c..f9f801360 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2,6 +2,15 @@ Run commands from the repository root. Start with the [project overview](../README.md) and [contribution guide](../CONTRIBUTING.md). Package-specific observations below used local inputs. Community regression tests use fixtures built from this repository. +## Graphics pipeline stream with a root SRV + +The source-built vertex shader fetches positions and colors through a root SRV at `t0, space3` using `SV_VertexID`. A VS/PS pipeline stream draws a fullscreen triangle with a different color at each vertex. Flat shading produces 64 green pixels. A zero vertex stride collapses the triangle and leaves all 64 pixels magenta. Binding an alternate range with a different leading color produces 64 red pixels. Each draw waits on its queue fence before comparing every RGBA byte. + +```powershell +cmake --build --preset release --target offscreen_check +ctest --preset release --no-tests=error -R '^stream_root_srv_' -V +``` + ## Local tools For optional static dependency inspection, build Microsoft's pinned version of xbdepends from PowerShell with x64 Visual Studio Build Tools, CMake and the Windows SDK. diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index cf8f7a400..346eae082 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -23,6 +23,7 @@ void check_ffx_device_init(ID3D12Device* device); void check_ffx_recurrent(ID3D12Device* device); void check_dual_uav(ID3D12Device* device); enum class DescriptorWindowCase { direct, stale_window, copied_record, stale_record, unknown_record }; +void check_stream_root_srv(ID3D12Device* device); void check_descriptor_window_submissions(ID3D12Device* device, DescriptorWindowCase scenario); enum class MeshConstantBinding { root, root_pair, swapped_root_pair, table, swapped_table }; enum class MeshDrawMode { color, textured, depth_pair }; diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 611385e04..e079c29f3 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -545,6 +545,12 @@ OperationResult run_dual_uav(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +OperationResult run_stream_root_srv(const OperationContext& ctx) +{ + check_stream_root_srv(ctx.device); + return {OutcomeKind::pass, nullptr}; +} + OperationResult run_descriptor_window_submissions(const OperationContext& ctx) { check_descriptor_window_submissions(ctx.device, DescriptorWindowCase::direct); @@ -992,6 +998,7 @@ const OperationSpec kOperations[] = { {"--ffx-provider-loop", 3, 3, nullptr, kNoGate, run_ffx_provider_loop}, {"--ffx-recurrent", 3, 3, nullptr, kNoGate, run_ffx_recurrent}, {"--dual-uav", 3, 3, nullptr, kNoGate, run_dual_uav}, + {"--stream-root-srv", 3, 3, nullptr, kGateSm60BufferOps, run_stream_root_srv}, {"--descriptor-window-submissions", 3, 3, nullptr, kGateSm60BufferOps, run_descriptor_window_submissions}, {"--descriptor-window-stale", 3, 3, nullptr, kGateSm60BufferOps, run_descriptor_window_stale}, {"--descriptor-record-copy", 4, 4, validate_descriptor_record_args, kGateSm60BufferOps, run_descriptor_record_copy}, diff --git a/tests/stream_root_srv.cpp b/tests/stream_root_srv.cpp new file mode 100644 index 000000000..c72a17472 --- /dev/null +++ b/tests/stream_root_srv.cpp @@ -0,0 +1,135 @@ +#include "desktop_gpu.h" +#include "stream_root_srv_vs.h" +#include "stream_root_srv_ps.h" + +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { +template +struct alignas(void*) Field { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE kind = Kind; + T value{}; +}; + +struct GraphicsStream { + Field root; + Field vs; + Field ps; + Field topology; + Field formats; + Field raster; + Field depth; +}; + +enum class Case { baseline, wrong_stride, wrong_binding }; + +void draw(ID3D12Device* device, ID3D12RootSignature* root, ID3D12PipelineState* pipeline, Case scenario) +{ + struct Vertex { float x, y; float color[4]; }; + struct Upload { UINT stride; UINT padding[3]; Vertex vertices[3]; }; + const Upload input{scenario == Case::wrong_stride ? 0u : UINT(sizeof(Vertex)), {}, + {{-1, -1, {0, 1, 0, 1}}, {-1, 3, {1, 0, 0, 1}}, {3, -1, {0, 0, 1, 1}}}}; + constexpr UINT alternate_offset = 256; + static_assert(sizeof(input) <= alternate_offset); + auto alternate = input; + alternate.vertices[0].color[0] = 1; + alternate.vertices[0].color[1] = 0; + auto upload = make_buffer(device, alternate_offset + sizeof(input), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped{}; + const D3D12_RANGE no_reads{}; + check(upload->Map(0, &no_reads, &mapped), "Map vertex data"); + std::memcpy(mapped, &input, sizeof(input)); + std::memcpy(static_cast(mapped) + alternate_offset, &alternate, sizeof(alternate)); + upload->Unmap(0, nullptr); + + constexpr UINT side = 8; + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = texture.Height = side; + texture.DepthOrArraySize = texture.MipLevels = texture.SampleDesc.Count = 1; + texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + D3D12_CLEAR_VALUE clear{texture.Format, {1, 0, 1, 1}}; + auto target = resource(device, texture, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &clear); + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + ComPtr heap; + check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "Create RTV heap"); + auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.Get(), nullptr, handle); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes{}; + device->GetCopyableFootprints(&texture, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + + ComputeCommands commands(device, pipeline, D3D12_COMMAND_LIST_TYPE_DIRECT); + auto* list = commands.list.Get(); + list->SetGraphicsRootSignature(root); + const UINT offset = scenario == Case::wrong_binding ? alternate_offset : 0; + list->SetGraphicsRootShaderResourceView(0, upload->GetGPUVirtualAddress() + offset); + const D3D12_VIEWPORT viewport{0, 0, side, side, 0, 1}; + const D3D12_RECT scissor{0, 0, side, side}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &handle, FALSE, nullptr); + list->ClearRenderTargetView(handle, clear.Color, 0, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + transition(list, target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION dst{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = footprint; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + commands.submit_and_wait(device); + + const std::array green{0, 255, 0, 255}, red{255, 0, 0, 255}, magenta{255, 0, 255, 255}; + auto expected = green; + if (scenario == Case::wrong_stride) expected = magenta; + if (scenario == Case::wrong_binding) expected = red; + check(readback->Map(0, nullptr, &mapped), "Map stream draw pixels"); + UINT mismatches{}; + for (UINT y = 0; y < side; ++y) { + const auto* row = static_cast(mapped) + footprint.Offset + y * footprint.Footprint.RowPitch; + for (UINT x = 0; x < side; ++x) + mismatches += std::memcmp(row + x * 4, expected.data(), expected.size()) != 0; + } + readback->Unmap(0, &no_reads); + std::printf("root_srv_offset=%u stride=%u pixels=%u mismatches=%u\n", offset, input.stride, side * side, mismatches); + if (mismatches) throw std::runtime_error("Graphics stream root SRV pixels differ"); +} +} + +void check_stream_root_srv(ID3D12Device* device) +{ + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + parameter.Descriptor = {0, 3}; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; + D3D12_ROOT_SIGNATURE_DESC root_desc{1, ¶meter}; + ComPtr blob; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr), "Serialize stream root"); + ComPtr root; + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)), "Create stream root"); + GraphicsStream stream{}; + stream.root.value = root.Get(); + stream.vs.value = {stream_root_srv_vs, sizeof(stream_root_srv_vs)}; + stream.ps.value = {stream_root_srv_ps, sizeof(stream_root_srv_ps)}; + stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + stream.formats.value.NumRenderTargets = 1; + stream.formats.value.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + stream.raster.value.FillMode = D3D12_FILL_MODE_SOLID; + stream.raster.value.CullMode = D3D12_CULL_MODE_NONE; + stream.raster.value.DepthClipEnable = TRUE; + stream.depth.value.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + ComPtr device2; + check(device->QueryInterface(IID_PPV_ARGS(&device2)), "Query pipeline stream device"); + ComPtr pipeline; + check(device2->CreatePipelineState(&desc, IID_PPV_ARGS(&pipeline)), "Create graphics stream"); + draw(device, root.Get(), pipeline.Get(), Case::baseline); + draw(device, root.Get(), pipeline.Get(), Case::wrong_stride); + draw(device, root.Get(), pipeline.Get(), Case::wrong_binding); +} diff --git a/tests/stream_root_srv.hlsl b/tests/stream_root_srv.hlsl new file mode 100644 index 000000000..f43e7daac --- /dev/null +++ b/tests/stream_root_srv.hlsl @@ -0,0 +1,20 @@ +ByteAddressBuffer vertices : register(t0, space3); + +struct Varyings { + float4 position : SV_Position; + nointerpolation float4 color : COLOR0; +}; + +Varyings VSMain(uint vertex : SV_VertexID) +{ + uint record = 16 + vertex * vertices.Load(0); + Varyings result; + result.position = float4(asfloat(vertices.Load2(record)), 0, 1); + result.color = asfloat(vertices.Load4(record + 8)); + return result; +} + +float4 PSMain(Varyings input) : SV_Target +{ + return input.color; +} From 9f23be2b232f96c9e48edb90c4cb9b97fb47bcdf Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 09:09:46 +0800 Subject: [PATCH 002/775] Refresh CPU-backed shader inputs after GPU readers retire --- CMakeLists.txt | 9 +++ docs/experiments.md | 14 +++++ src/cpu_srv_upload.h | 54 ++++++++++++++++++ tests/cpu_srv_refresh.hlsl | 8 +++ tests/descriptor_window_submissions.cpp | 76 +++++++++++++++++++++++++ tests/desktop_gpu.h | 1 + tests/offscreen_check.cpp | 8 +++ 7 files changed, 170 insertions(+) create mode 100644 src/cpu_srv_upload.h create mode 100644 tests/cpu_srv_refresh.hlsl diff --git a/CMakeLists.txt b/CMakeLists.txt index 841f3c064..6d85848de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -274,6 +274,11 @@ add_custom_command(OUTPUT "${descriptor_window_cs}" COMMAND "${DXC_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/descriptor_window_submissions.hlsl" DEPENDS tests/descriptor_window_submissions.hlsl VERBATIM) target_sources(offscreen_check PRIVATE tests/descriptor_window_submissions.cpp "${descriptor_window_cs}") +set(cpu_srv_cs "${CMAKE_CURRENT_BINARY_DIR}/cpu_srv_refresh_cs.h") +add_custom_command(OUTPUT "${cpu_srv_cs}" COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E main + -Vn cpu_srv_refresh_cs -Fh "${cpu_srv_cs}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/cpu_srv_refresh.hlsl" + DEPENDS tests/cpu_srv_refresh.hlsl VERBATIM) +target_sources(offscreen_check PRIVATE "${cpu_srv_cs}") target_sources(offscreen_check PRIVATE tests/binding_mips.cpp tests/ffx_recurrent_views.cpp) target_sources(offscreen_check PRIVATE tests/ffx_rcas_views.cpp) foreach(storage IN ITEMS Native Packed) @@ -538,6 +543,10 @@ foreach(adapter IN ITEMS hardware warp) add_test(NAME ffx_recurrent_${adapter} COMMAND offscreen_check ${adapter} --ffx-recurrent) add_test(NAME dual_uav_${adapter} COMMAND offscreen_check ${adapter} --dual-uav) add_test(NAME descriptor_window_submissions_${adapter} COMMAND offscreen_check ${adapter} --descriptor-window-submissions) + foreach(mode IN ITEMS refresh stale) + add_test(NAME cpu_srv_${mode}_${adapter} COMMAND offscreen_check ${adapter} --cpu-srv-${mode}) + set_tests_properties(cpu_srv_${mode}_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME descriptor_window_stale_${adapter} COMMAND offscreen_check ${adapter} --descriptor-window-stale) set_tests_properties(descriptor_window_submissions_${adapter} descriptor_window_stale_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) diff --git a/docs/experiments.md b/docs/experiments.md index 478099ba9..78bb382b5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4463,6 +4463,20 @@ ctest --preset dev --no-tests=error -R '^descriptor_window_' -V Repeat with the `release` preset. +#### CPU input changes between submissions + +The source-built compute fixture binds one `R16_UINT` SRV over an upload buffer +for both submissions. After fence 1 the CPU changes two elements. Refreshing +the same upload range before submission 2 changes the shader readback from +`1398 2467` to `8765 fe01` (hex). The stale control omits that refresh and +reads the first pair again. An incomplete fence, an out-of-range write and an +unreadable source page are rejected before the live data changes. + +Build `offscreen_check` and run +`ctest --preset release --no-tests=error -R '^cpu_srv_' -V`. +The caller owns source lifetime and must retire all queues reading an upload +range before refreshing it. + #### CPU-copied binding records `descriptor_record_copy` reuses the same shader and submission sequence. After fence 1, the test copies a 32-byte CPU binding record into the second record with `memcpy`. The live path reads the copied ID and uses `CopyDescriptorsSimple` to transfer its SRV from a CPU-only staging heap to shader-visible slot 999,999. The stale control reads a saved record while binding that same GPU slot. The records contain fixture-defined IDs and are independent of the opaque D3D12 descriptors. [Startup observation on #870](https://github.com/R0Y00/Xbox2Windows/issues/870#issuecomment-7116272710) · [Microsoft descriptor-copy guidance](https://learn.microsoft.com/en-us/windows/win32/direct3d12/copying-descriptors) diff --git a/src/cpu_srv_upload.h b/src/cpu_srv_upload.h new file mode 100644 index 000000000..28f004201 --- /dev/null +++ b/src/cpu_srv_upload.h @@ -0,0 +1,54 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace cpu_srv { + +// Refresh a caller-owned upload buffer before submitting work that reads its +// SRV. The caller serializes refresh/submit, keeps the source stable during +// this call and supplies the fence point covering all preceding GPU reads. +// With multiple queues, join the previous readers before using a single point. +// A null fence with value zero denotes the first use (or external retirement). +inline HRESULT refresh(ID3D12Resource* upload, SIZE_T destination_offset, + const void* source, SIZE_T bytes, ID3D12Fence* previous_fence, + UINT64 previous_value) +{ + if (!upload || !source || !bytes || (!previous_fence && previous_value)) return E_INVALIDARG; + const auto desc = upload->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + destination_offset > desc.Width || bytes > desc.Width - destination_offset) return E_INVALIDARG; + D3D12_HEAP_PROPERTIES heap{}; + D3D12_HEAP_FLAGS flags{}; + HRESULT hr = upload->GetHeapProperties(&heap, &flags); + if (FAILED(hr)) return hr; + if (heap.Type != D3D12_HEAP_TYPE_UPLOAD) return E_INVALIDARG; + if (previous_fence) { + const UINT64 done = previous_fence->GetCompletedValue(); + if (done == UINT64_MAX) return DXGI_ERROR_DEVICE_REMOVED; + if (done < previous_value) return DXGI_ERROR_WAS_STILL_DRAWING; + } + + // A source may straddle an unreadable page. Stage the complete read before + // changing the live upload so a rejected refresh preserves its old contents. + auto copy = std::unique_ptr(new (std::nothrow) std::byte[bytes]); + if (!copy) return E_OUTOFMEMORY; + SIZE_T copied{}; + if (!ReadProcessMemory(GetCurrentProcess(), source, copy.get(), bytes, &copied)) + return HRESULT_FROM_WIN32(GetLastError()); + if (copied != bytes) return HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY); + const D3D12_RANGE no_read{0, 0}; + void* mapped{}; + hr = upload->Map(0, &no_read, &mapped); + if (FAILED(hr)) return hr; + std::memcpy(static_cast(mapped) + destination_offset, copy.get(), bytes); + const D3D12_RANGE written{destination_offset, destination_offset + bytes}; + upload->Unmap(0, &written); + return S_OK; +} + +} // namespace cpu_srv diff --git a/tests/cpu_srv_refresh.hlsl b/tests/cpu_srv_refresh.hlsl new file mode 100644 index 000000000..e80b8730d --- /dev/null +++ b/tests/cpu_srv_refresh.hlsl @@ -0,0 +1,8 @@ +Buffer inputWords : register(t0); +RWByteAddressBuffer result : register(u0); + +[numthreads(1, 1, 1)] +void main() +{ + result.Store2(0, uint2(inputWords.Load(0), inputWords.Load(1))); +} diff --git a/tests/descriptor_window_submissions.cpp b/tests/descriptor_window_submissions.cpp index f42a5616e..6114d4d38 100644 --- a/tests/descriptor_window_submissions.cpp +++ b/tests/descriptor_window_submissions.cpp @@ -1,4 +1,6 @@ #include "desktop_gpu.h" +#include "../src/cpu_srv_upload.h" +#include "cpu_srv_refresh_cs.h" #include "descriptor_window_submissions_cs.h" #include @@ -214,3 +216,77 @@ void check_descriptor_window_submissions(ID3D12Device* device, DescriptorWindowC compare_words(fence_value, read_words(readback.Get()), expected[i]); } } + +void check_cpu_srv_refresh(ID3D12Device* device, bool stale) +{ + const auto root = create_root(device); + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root.Get(); + desc.CS = {cpu_srv_refresh_cs, sizeof(cpu_srv_refresh_cs)}; + ComPtr pipeline; + check(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pipeline)), "Create CPU-SRV pipeline"); + ComputeCommands commands(device, pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + ComPtr retire; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&retire)), "Create CPU-SRV fence"); + constexpr UINT first = 16; + constexpr UINT bytes = first + 2 * sizeof(UINT16); + const auto upload = make_buffer(device, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + const auto output = make_buffer(device, sizeof(Words), D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto readback = make_buffer(device, sizeof(Words), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ComPtr heap; + check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "Create CPU-SRV heap"); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Format = DXGI_FORMAT_R16_UINT; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.FirstElement = first / sizeof(UINT16); + srv.Buffer.NumElements = 2; + device->CreateShaderResourceView(upload.Get(), &srv, heap->GetCPUDescriptorHandleForHeapStart()); + + constexpr std::array original{0x1398, 0x2467}, replacement{0x8765, 0xfe01}; + auto source = original; + check(cpu_srv::refresh(upload.Get(), first, source.data(), sizeof(source), nullptr, 0), "Refresh initial SRV"); + for (UINT i = 0; i < 2; ++i) { + auto* list = commands.list.Get(); + if (i == 1) { + source = replacement; + if (cpu_srv::refresh(upload.Get(), first, source.data(), sizeof(source), retire.Get(), 2) != + DXGI_ERROR_WAS_STILL_DRAWING || + cpu_srv::refresh(upload.Get(), first + 1, source.data(), sizeof(source), retire.Get(), 1) != E_INVALIDARG || + cpu_srv::refresh(upload.Get(), SIZE_MAX, source.data(), sizeof(source), retire.Get(), 1) != E_INVALIDARG) + throw std::runtime_error("CPU-SRV accepted an outstanding fence or an out-of-range refresh"); + auto* inaccessible = VirtualAlloc(nullptr, 1, MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS); + if (!inaccessible) throw std::runtime_error("Cannot allocate unreadable CPU-SRV control"); + const HRESULT rejected = cpu_srv::refresh(upload.Get(), first, inaccessible, sizeof(source), retire.Get(), 1); + VirtualFree(inaccessible, 0, MEM_RELEASE); + if (SUCCEEDED(rejected)) throw std::runtime_error("CPU-SRV accepted unreadable input"); + if (!stale) + check(cpu_srv::refresh(upload.Get(), first, source.data(), sizeof(source), retire.Get(), 1), + "Refresh SRV after fence"); + check(commands.allocator->Reset(), "Reset CPU-SRV allocator"); + check(list->Reset(commands.allocator.Get(), pipeline.Get()), "Reset CPU-SRV list"); + } + transition(list, output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->SetComputeRootSignature(root.Get()); + ID3D12DescriptorHeap* heaps[]{heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootDescriptorTable(0, heap->GetGPUDescriptorHandleForHeapStart()); + list->SetComputeRootUnorderedAccessView(1, output->GetGPUVirtualAddress()); + list->SetComputeRoot32BitConstant(2, 0, 0); + list->Dispatch(1, 1, 1); + transition(list, output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(readback.Get(), output.Get()); + transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + check(list->Close(), "Close CPU-SRV list"); + ID3D12CommandList* batch[]{list}; + commands.queue->ExecuteCommandLists(1, batch); + check(commands.queue->Signal(retire.Get(), i + 1), "Signal CPU-SRV fence"); + check(retire->SetEventOnCompletion(i + 1, nullptr), "Wait for CPU-SRV fence"); + check(device->GetDeviceRemovedReason(), "Complete CPU-SRV read"); + const auto expected = (i == 1 && !stale) ? replacement : original; + compare_words(i + 1, read_words(readback.Get()), {expected[0], expected[1]}); + } +} diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index cf8f7a400..89a197d8b 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -24,6 +24,7 @@ void check_ffx_recurrent(ID3D12Device* device); void check_dual_uav(ID3D12Device* device); enum class DescriptorWindowCase { direct, stale_window, copied_record, stale_record, unknown_record }; void check_descriptor_window_submissions(ID3D12Device* device, DescriptorWindowCase scenario); +void check_cpu_srv_refresh(ID3D12Device* device, bool stale); enum class MeshConstantBinding { root, root_pair, swapped_root_pair, table, swapped_table }; enum class MeshDrawMode { color, textured, depth_pair }; struct MeshTextureProducers { diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index f3a2642af..77609324e 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -553,6 +553,12 @@ OperationResult run_descriptor_window_submissions(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +OperationResult run_cpu_srv_refresh(const OperationContext& ctx) +{ + check_cpu_srv_refresh(ctx.device, std::string_view(ctx.argv[2]) == "--cpu-srv-stale"); + return {OutcomeKind::pass, nullptr}; +} + OperationResult run_descriptor_window_stale(const OperationContext& ctx) { check_descriptor_window_submissions(ctx.device, DescriptorWindowCase::stale_window); @@ -1002,6 +1008,8 @@ const OperationSpec kOperations[] = { {"--ffx-recurrent", 3, 3, nullptr, kNoGate, run_ffx_recurrent}, {"--dual-uav", 3, 3, nullptr, kNoGate, run_dual_uav}, {"--descriptor-window-submissions", 3, 3, nullptr, kGateSm60BufferOps, run_descriptor_window_submissions}, + {"--cpu-srv-refresh", 3, 3, nullptr, kGateSm60BufferOps, run_cpu_srv_refresh}, + {"--cpu-srv-stale", 3, 3, nullptr, kGateSm60BufferOps, run_cpu_srv_refresh}, {"--descriptor-window-stale", 3, 3, nullptr, kGateSm60BufferOps, run_descriptor_window_stale}, {"--descriptor-record-copy", 4, 4, validate_descriptor_record_args, kGateSm60BufferOps, run_descriptor_record_copy}, {"--texture-mips", 3, 3, nullptr, kNoGate, run_texture_mips}, From e132e457749fae026c32469cb7ccb70eea76f4c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Batuhan=20=C5=9Eahin?= <54989644+Batushn@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:53:33 +0300 Subject: [PATCH 003/775] cpu: lower PF consumers after VEX scalar compares --- CMakeLists.txt | 25 ++ docs/experiments.md | 40 ++- tests/cpu/vex_parity.asm | 318 ++++++++++++++++++++++++ tests/cpu/vex_parity.def | 15 ++ tests/cpu/vex_parity.py | 488 +++++++++++++++++++++++++++++++++++++ tests/cpu/x87_compare.py | 6 +- tests/cpu/x87_parity.py | 5 +- tools/ffx_version_query.py | 23 +- tools/x87_lower.py | 50 ++-- 9 files changed, 939 insertions(+), 31 deletions(-) create mode 100644 tests/cpu/vex_parity.asm create mode 100644 tests/cpu/vex_parity.def create mode 100644 tests/cpu/vex_parity.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 109001076..70d37164a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2378,6 +2378,31 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME cpu_aot_avx_scalar_fp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/avx_scalar_fp.py" check "$" "$") set_tests_properties(cpu_aot_avx_scalar_fp PROPERTIES SKIP_RETURN_CODE 77) + cpu_asm_fixture(cpu_vex_parity vex_parity) + # The lifted DLL, an explicit /O2 build, and two mutated controls (stalepf, swap) that must mismatch. + set(vex_parity_control_files "") + foreach(variant IN ITEMS lifted stalepf swap) + set(vex_parity_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_vex_parity_${variant}.cpp") + add_custom_command(OUTPUT "${vex_parity_fixture}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/vex_parity.py" + emit "$" "${vex_parity_fixture}" ${variant} + DEPENDS cpu_vex_parity tests/cpu/vex_parity.py tools/ffx_version_query.py tools/x87_lower.py + tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_vex_parity_${variant} SHARED "${vex_parity_fixture}") + if(NOT variant STREQUAL "lifted") + list(APPEND vex_parity_control_files "$") + endif() + endforeach() + set(vex_parity_o2 "${CMAKE_CURRENT_BINARY_DIR}/cpu_vex_parity_lifted_o2.dll") + add_custom_command(OUTPUT "${vex_parity_o2}" + COMMAND "${CMAKE_CXX_COMPILER}" /nologo /O2 /W4 /EHsc /LD "${CMAKE_CURRENT_BINARY_DIR}/cpu_vex_parity_lifted.cpp" + "/Fo${CMAKE_CURRENT_BINARY_DIR}/cpu_vex_parity_lifted_o2.obj" "/Fe${vex_parity_o2}" + DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/cpu_vex_parity_lifted.cpp" VERBATIM) + add_custom_target(cpu_vex_parity_lifted_o2 ALL DEPENDS "${vex_parity_o2}") + add_test(NAME cpu_aot_vex_parity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/vex_parity.py" + check "$" "$" + "$" "${vex_parity_o2}" ${vex_parity_control_files}) + set_tests_properties(cpu_aot_vex_parity PROPERTIES SKIP_RETURN_CODE 77) cpu_translation(cpu_callback cpu_chained_aot call_context CALLBACK_OFFSET 8) cpu_asm_fixture(cpu_xlatb xlatb) # The lifted DLL and three mutated controls that the check requires to mismatch. diff --git a/docs/experiments.md b/docs/experiments.md index 8e76c9fd9..4da5cf115 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1410,7 +1410,7 @@ The model compares with the `Fraction` model of `cpu_aot_x87_compare` and copies | `uinvert` | `fcmovu` moves on a clear PF | 4050/17672 | 1522 in `fucomi_fcmovu` | | `nuinvert` | `fcmovnu` moves on a set PF | 2122/17672 | 1522 in `fcomi_fcmovnu` | -`pfkeep` mismatches in `sahf_fucomi` only where the `sahf` before `fucomi` left a different PF. On the AMD Ryzen 7 7700 and the Intel Core Ultra 7 358H (Windows 11 build 26300) every case matched in the native and translated DLLs. Translation rejects 10 sequences: `fcmovu` before any flag writer, `fcmovnu` after `test eax, eax`, `fcmovu` after `fucomi` and `inc eax`, `jp` after `fucomi` and `add eax, 1`, `fcmovu` after a call, a join of a `fucomi` path and a `cmp` path, `sahf` on `fnstsw ax` without a comparison before `fcmovu`, `fcmovu st, st(2)` with two values, `fcmovnu st, st(1)` with one value, and `setp` after `fucomi`, which the integer lowering does not implement. It translates 5 twins: `fcmovu` after `fucomi`, `fcmovnu` after `fucomi` and a `mov`, `jp` after `fucomip` and `fstp st(0)`, a join of a `fucomi` path and a `sahf` path, and `fcmovu` after `fucomi` and `lea`. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_parity$' -V`. +`pfkeep` mismatches in `sahf_fucomi` only where the `sahf` before `fucomi` left a different PF. On the AMD Ryzen 7 7700 and the Intel Core Ultra 7 358H (Windows 11 build 26300) every case matched in the native and translated DLLs. Translation rejects 11 sequences: `fcmovu` before any flag writer, `fcmovnu` after `test eax, eax`, `fcmovu` after `fucomi` and `inc eax`, `jp` after `fucomi` and `add eax, 1`, `fcmovu` after a call, a join of a `fucomi` path and a `cmp` path, `sahf` on `fnstsw ax` without a comparison before `fcmovu`, `fcmovu st, st(2)` with two values, `fcmovnu st, st(1)` with one value, `setp` after `fucomi` and `inc eax`, and `cmovp` after `fucomi` and `add eax, 1`. It translates 7 accepted sequences: `fcmovu` after `fucomi`, `fcmovnu` after `fucomi` and a `mov`, `jp` after `fucomip` and `fstp st(0)`, a join of a `fucomi` path and a `sahf` path, `fcmovu` after `fucomi` and `lea`, `setp` after `fucomi`, and `cmovp` after `fucomi`. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_parity$' -V`. `cpu_aot_x87_fprem` checks `fprem` and `fprem1` in the checked entry, with 11 exports and 36952 cases. The fixed profile rejects both. Each replaces `st(0)` by `st(0) - q * st(1)`. q is the quotient of the magnitudes, truncated by `fprem` and rounded to nearest-even by `fprem1`. Each sets C0, C3 and C1 to bits 2, 1 and 0 of q and clears C2. The remainder is exact. A zero remainder keeps the sign of `st(0)`, a zero `st(0)` is kept, and an infinite `st(1)` gives `st(0)` with q = 0. A pseudo-denormal is re-encoded at biased exponent 1. Neither instruction reads the control word. The SDM leaves two outcomes to the implementation, and the checked entry rejects both: @@ -7266,3 +7266,41 @@ python3 -B tests/rdna2_tools_check.py Scope: decoding and scanner recognition only. None of these forms is lowered by a translator, and no measurement on hardware or in a Windows run backs the descriptions. + +## PF consumers after scalar VEX compares + +`tools/ffx_version_query.py` and `tools/x87_lower.py` lower `SETP`, `SETNP`, `CMOVP`, and `CMOVNP` alongside +`JP` and `JNP` whenever `x87_lower.check_flags` proves a reaching modeled PF definition at every use. +`x87_lower.assigns_parity` treats the four scalar VEX compares (`vcomiss`, `vucomiss`, `vcomisd`, +`vucomisd`) and the already modeled PF-clearing instructions (`rdrand`, `rdseed`, `ptest`, `vptest`, +`vtestps`, `vtestpd`, `pcmpestri`, `pcmpestrm`, `pcmpistri`, `pcmpistrm`) as PF producers in addition to +`sahf`, `fcomi`/`fcomip`/`fucomi`/`fucomip`, and 8-bit `test`/`and`. Indirect branches in functions with +PF consumers are rejected, `host_ops` replacements invalidate tracked flags/PF, and functions without PF +consumers emit unchanged parity-free C++. + +[tests/cpu/vex_parity.asm](../tests/cpu/vex_parity.asm) and +[tests/cpu/vex_parity.py](../tests/cpu/vex_parity.py) (`cpu_aot_vex_parity`) compare native, translated, +and `/O2` DLLs across 14 exports and 1618 cases under masked `MXCSR = 0x1F80` (saved and restored via +`host_exchange_mxcsr`): + +- Register and memory RHS forms for `vcomiss`, `vucomiss`, `vcomisd`, and `vucomisd`, covering ordered + (`<`, `==`, `>`), signed zeros, `+/-inf`, subnormals, quiet NaNs, and signaling NaNs in each operand + (consumed through `setp`, `setnp`, `sete`, `setb`, `jp`, `jnp`, and `setnp + sete + and`). +- `setp al` / `setnp ah` upper-byte preservation, and both outcomes (`PF = 0` and `PF = 1`) of `cmovp` / + `cmovnp` at 32-bit (zero-extending upper 32 bits even when not taken), 64-bit, and 16-bit widths. +- Unconditional memory reads (`0xC0000005` on `PAGE_NOACCESS` and `NULL` via `cpu_guarded_call`) for + `cmovp eax, dword ptr [rdx]` and `cmovnp eax, dword ptr [rdx]` regardless of whether `PF` is 0 or 1. +- A `vcomiss` / `vucomisd` control-flow join and a back-to-back compare override (`vucomiss` followed by `vcomiss`). +- Two mutated controls that must fail (`stalepf` dropping `parity = unordered;` caught 3 mismatches; `swap` + reversing PF consumer conditions caught 5 mismatches), plus 13 rejected sequences (entry/no writer, `add`, + `cmp`, `inc`, 32-bit `test`, `shl`, `call`, ambiguous/uninitialized joins, indirect branch, `host_ops`) and + 4 accepted sequences. + +```sh +ctest --preset dev --no-tests=error -R "^cpu_aot_vex_parity$" -V +ctest --preset release --no-tests=error -R "^cpu_aot_vex_parity$" -V +``` + +Scope: masked `MXCSR = 0x1F80` scalar VEX comparisons and proven reaching PF consumers only; existing +floating-point exception behavior outside `vex_parity` is unchanged, and unmodeled PF producers or +ambiguous joins remain rejected. diff --git a/tests/cpu/vex_parity.asm b/tests/cpu/vex_parity.asm new file mode 100644 index 000000000..748bde230 --- /dev/null +++ b/tests/cpu/vex_parity.asm @@ -0,0 +1,318 @@ +; coverage: source cpu_aot_vex_parity +; Source-owned differential fixture for PF after VCOMISS/VUCOMISS/VCOMISD/VUCOMISD and +; SETP/SETNP/CMOVP/CMOVNP/JP/JNP lowering (plus CFG joins and memory-read fault checks). +.code + +vcomiss_reg_flags PROC FRAME + .endprolog + vmovss xmm0, dword ptr [rcx] + vmovss xmm1, dword ptr [rdx] + vcomiss xmm0, xmm1 + setp byte ptr [r8+0] + setnp byte ptr [r8+1] + sete byte ptr [r8+2] + setb byte ptr [r8+3] + mov byte ptr [r8+4], 1 + jp vcomiss_reg_jp + mov byte ptr [r8+4], 0 +vcomiss_reg_jp: + mov byte ptr [r8+5], 1 + jnp vcomiss_reg_jnp + mov byte ptr [r8+5], 0 +vcomiss_reg_jnp: + setnp al + sete ah + and al, ah + mov byte ptr [r8+6], al + xor eax, eax + vzeroupper + ret +vcomiss_reg_flags ENDP + +vcomiss_mem_flags PROC FRAME + .endprolog + vmovss xmm0, dword ptr [rcx] + vcomiss xmm0, dword ptr [rdx] + setp byte ptr [r8+0] + setnp byte ptr [r8+1] + sete byte ptr [r8+2] + setb byte ptr [r8+3] + mov byte ptr [r8+4], 1 + jp vcomiss_mem_jp + mov byte ptr [r8+4], 0 +vcomiss_mem_jp: + mov byte ptr [r8+5], 1 + jnp vcomiss_mem_jnp + mov byte ptr [r8+5], 0 +vcomiss_mem_jnp: + setnp al + sete ah + and al, ah + mov byte ptr [r8+6], al + xor eax, eax + vzeroupper + ret +vcomiss_mem_flags ENDP + +vucomiss_reg_flags PROC FRAME + .endprolog + vmovss xmm0, dword ptr [rcx] + vmovss xmm1, dword ptr [rdx] + vucomiss xmm0, xmm1 + setp byte ptr [r8+0] + setnp byte ptr [r8+1] + sete byte ptr [r8+2] + setb byte ptr [r8+3] + mov byte ptr [r8+4], 1 + jp vucomiss_reg_jp + mov byte ptr [r8+4], 0 +vucomiss_reg_jp: + mov byte ptr [r8+5], 1 + jnp vucomiss_reg_jnp + mov byte ptr [r8+5], 0 +vucomiss_reg_jnp: + setnp al + sete ah + and al, ah + mov byte ptr [r8+6], al + xor eax, eax + vzeroupper + ret +vucomiss_reg_flags ENDP + +vucomiss_mem_flags PROC FRAME + .endprolog + vmovss xmm0, dword ptr [rcx] + vucomiss xmm0, dword ptr [rdx] + setp byte ptr [r8+0] + setnp byte ptr [r8+1] + sete byte ptr [r8+2] + setb byte ptr [r8+3] + mov byte ptr [r8+4], 1 + jp vucomiss_mem_jp + mov byte ptr [r8+4], 0 +vucomiss_mem_jp: + mov byte ptr [r8+5], 1 + jnp vucomiss_mem_jnp + mov byte ptr [r8+5], 0 +vucomiss_mem_jnp: + setnp al + sete ah + and al, ah + mov byte ptr [r8+6], al + xor eax, eax + vzeroupper + ret +vucomiss_mem_flags ENDP + +vcomisd_reg_flags PROC FRAME + .endprolog + vmovsd xmm0, qword ptr [rcx] + vmovsd xmm1, qword ptr [rdx] + vcomisd xmm0, xmm1 + setp byte ptr [r8+0] + setnp byte ptr [r8+1] + sete byte ptr [r8+2] + setb byte ptr [r8+3] + mov byte ptr [r8+4], 1 + jp vcomisd_reg_jp + mov byte ptr [r8+4], 0 +vcomisd_reg_jp: + mov byte ptr [r8+5], 1 + jnp vcomisd_reg_jnp + mov byte ptr [r8+5], 0 +vcomisd_reg_jnp: + setnp al + sete ah + and al, ah + mov byte ptr [r8+6], al + xor eax, eax + vzeroupper + ret +vcomisd_reg_flags ENDP + +vcomisd_mem_flags PROC FRAME + .endprolog + vmovsd xmm0, qword ptr [rcx] + vcomisd xmm0, qword ptr [rdx] + setp byte ptr [r8+0] + setnp byte ptr [r8+1] + sete byte ptr [r8+2] + setb byte ptr [r8+3] + mov byte ptr [r8+4], 1 + jp vcomisd_mem_jp + mov byte ptr [r8+4], 0 +vcomisd_mem_jp: + mov byte ptr [r8+5], 1 + jnp vcomisd_mem_jnp + mov byte ptr [r8+5], 0 +vcomisd_mem_jnp: + setnp al + sete ah + and al, ah + mov byte ptr [r8+6], al + xor eax, eax + vzeroupper + ret +vcomisd_mem_flags ENDP + +vucomisd_reg_flags PROC FRAME + .endprolog + vmovsd xmm0, qword ptr [rcx] + vmovsd xmm1, qword ptr [rdx] + vucomisd xmm0, xmm1 + setp byte ptr [r8+0] + setnp byte ptr [r8+1] + sete byte ptr [r8+2] + setb byte ptr [r8+3] + mov byte ptr [r8+4], 1 + jp vucomisd_reg_jp + mov byte ptr [r8+4], 0 +vucomisd_reg_jp: + mov byte ptr [r8+5], 1 + jnp vucomisd_reg_jnp + mov byte ptr [r8+5], 0 +vucomisd_reg_jnp: + setnp al + sete ah + and al, ah + mov byte ptr [r8+6], al + xor eax, eax + vzeroupper + ret +vucomisd_reg_flags ENDP + +vucomisd_mem_flags PROC FRAME + .endprolog + vmovsd xmm0, qword ptr [rcx] + vucomisd xmm0, qword ptr [rdx] + setp byte ptr [r8+0] + setnp byte ptr [r8+1] + sete byte ptr [r8+2] + setb byte ptr [r8+3] + mov byte ptr [r8+4], 1 + jp vucomisd_mem_jp + mov byte ptr [r8+4], 0 +vucomisd_mem_jp: + mov byte ptr [r8+5], 1 + jnp vucomisd_mem_jnp + mov byte ptr [r8+5], 0 +vucomisd_mem_jnp: + setnp al + sete ah + and al, ah + mov byte ptr [r8+6], al + xor eax, eax + vzeroupper + ret +vucomisd_mem_flags ENDP + +setp_reg_bytes PROC FRAME + .endprolog + vmovss xmm0, dword ptr [rcx] + vmovss xmm1, dword ptr [rdx] + mov rax, r8 + vcomiss xmm0, xmm1 + setp al + setnp ah + vzeroupper + ret +setp_reg_bytes ENDP + +cmov_reg_outcomes PROC FRAME + .endprolog + vmovss xmm0, dword ptr [rcx] + vmovss xmm1, dword ptr [rdx] + vcomiss xmm0, xmm1 + mov r10, 1122334455667788h + cmovp r10d, r8d + mov qword ptr [r9+0], r10 + mov r10, 1122334455667788h + cmovnp r10d, r8d + mov qword ptr [r9+8], r10 + mov r10, 1122334455667788h + cmovp r10, r8 + mov qword ptr [r9+16], r10 + mov r10, 1122334455667788h + cmovnp r10, r8 + mov qword ptr [r9+24], r10 + mov r10, 1122334455667788h + cmovp r10w, r8w + mov qword ptr [r9+32], r10 + mov r10, 1122334455667788h + cmovnp r10w, r8w + mov qword ptr [r9+40], r10 + xor eax, eax + vzeroupper + ret +cmov_reg_outcomes ENDP + +cmovp_mem32 PROC FRAME + .endprolog + vmovss xmm0, dword ptr [rcx] + vmovss xmm1, dword ptr [rcx+4] + mov rax, 1122334455667788h + vcomiss xmm0, xmm1 + cmovp eax, dword ptr [rdx] + vzeroupper + ret +cmovp_mem32 ENDP + +cmovnp_mem32 PROC FRAME + .endprolog + vmovss xmm0, dword ptr [rcx] + vmovss xmm1, dword ptr [rcx+4] + mov rax, 1122334455667788h + vcomiss xmm0, xmm1 + cmovnp eax, dword ptr [rdx] + vzeroupper + ret +cmovnp_mem32 ENDP + +join_vcomi_pf PROC FRAME + .endprolog + test r8d, r8d + je join_vcomi_pf_alt + vmovss xmm0, dword ptr [rcx] + vmovss xmm1, dword ptr [rdx] + vcomiss xmm0, xmm1 + jmp join_vcomi_pf_join +join_vcomi_pf_alt: + vmovsd xmm0, qword ptr [rcx+8] + vmovsd xmm1, qword ptr [rdx+8] + vucomisd xmm0, xmm1 +join_vcomi_pf_join: + mov rax, 1122334455667788h + mov r10d, 0abcdef01h + cmovp eax, r10d + mov qword ptr [r9+0], rax + setp byte ptr [r9+8] + mov byte ptr [r9+9], 1 + jp join_vcomi_pf_jp + mov byte ptr [r9+9], 0 +join_vcomi_pf_jp: + xor eax, eax + vzeroupper + ret +join_vcomi_pf ENDP + +back_to_back_vcomi PROC FRAME + .endprolog + vmovss xmm0, dword ptr [rcx] + vmovss xmm1, dword ptr [rdx] + vucomiss xmm0, xmm1 + vmovss xmm0, dword ptr [rcx+4] + vmovss xmm1, dword ptr [rdx+4] + vcomiss xmm0, xmm1 + setp byte ptr [r8+0] + setnp byte ptr [r8+1] + mov rax, 1122334455667788h + mov r10d, 0abcdef01h + cmovp eax, r10d + mov qword ptr [r8+8], rax + xor eax, eax + vzeroupper + ret +back_to_back_vcomi ENDP + +END diff --git a/tests/cpu/vex_parity.def b/tests/cpu/vex_parity.def new file mode 100644 index 000000000..1d690b777 --- /dev/null +++ b/tests/cpu/vex_parity.def @@ -0,0 +1,15 @@ +EXPORTS + vcomiss_reg_flags + vcomiss_mem_flags + vucomiss_reg_flags + vucomiss_mem_flags + vcomisd_reg_flags + vcomisd_mem_flags + vucomisd_reg_flags + vucomisd_mem_flags + setp_reg_bytes + cmov_reg_outcomes + cmovp_mem32 + cmovnp_mem32 + join_vcomi_pf + back_to_back_vcomi diff --git a/tests/cpu/vex_parity.py b/tests/cpu/vex_parity.py new file mode 100644 index 000000000..03aeb3139 --- /dev/null +++ b/tests/cpu/vex_parity.py @@ -0,0 +1,488 @@ +"""Differential check for PF after VEX scalar compares (VCOMISS/VUCOMISS/VCOMISD/VUCOMISD) +and PF consumers (SETP/SETNP/CMOVP/CMOVNP/JP/JNP), including /O2, fault checks, and mutated controls. + +Usage: + python tests/cpu/vex_parity.py emit [control] + python tests/cpu/vex_parity.py check [controls...] +""" +import ctypes +from pathlib import Path +import platform +import re +import struct +import sys + +import pefile +from iced_x86 import Decoder + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "tools")) +from cpu_leaf_aot import export_rva # noqa: E402 +from cpu_ranges import function_ranges # noqa: E402 +from ffx_version_query import INTEGER_HEADER, lower, region # noqa: E402 + +FLAG_EXPORTS = ( + "vcomiss_reg_flags", "vcomiss_mem_flags", + "vucomiss_reg_flags", "vucomiss_mem_flags", + "vcomisd_reg_flags", "vcomisd_mem_flags", + "vucomisd_reg_flags", "vucomisd_mem_flags", +) +FOUR_ARG_EXPORTS = FLAG_EXPORTS + ( + "setp_reg_bytes", + "cmov_reg_outcomes", + "join_vcomi_pf", + "back_to_back_vcomi", +) +THREE_ARG_EXPORTS = ("cmovp_mem32", "cmovnp_mem32") +ALL_EXPORTS = FOUR_ARG_EXPORTS + THREE_ARG_EXPORTS + +PAGE = 0x1000 +ACCESS_VIOLATION = 0xC0000005 +MXCSR_ALL_MASKED = 0x1F80 # IE..PE masked, round-to-nearest, DAZ=0, FTZ=0 + +CPUID_HELPER = """#include +extern "C" __declspec(dllexport) uint32_t host_has_avx() { + int info[4]{}; + __cpuid(info, 1); + const int need = (1 << 27) | (1 << 28); + if ((info[2] & need) != need) return 0u; + return (_xgetbv(0) & 6u) == 6u ? 1u : 0u; +} +extern "C" __declspec(dllexport) uint32_t host_exchange_mxcsr(uint32_t next) { + const uint32_t current = _mm_getcsr(); + _mm_setcsr(next); + return current; +} +""" + +PARITY_USE_RE = re.compile(r"(? str: + if control == "lifted": + return cpp + if control == "stalepf": + mutated, count = re.subn(r" parity = unordered;", "", cpp) + if count == 0: + raise AssertionError("stalepf control matched zero 'parity = unordered;' statements") + return mutated + if control == "swap": + mutated, count = PARITY_USE_RE.subn( + lambda m: "parity" if m.group(1).startswith("!") else "!parity", cpp + ) + if count == 0: + raise AssertionError("swap control matched zero PF consumer conditions") + return mutated + raise ValueError(f"unknown control variant: {control}") + + +def emit(native_dll: Path, output_cpp: Path, control: str = "lifted") -> None: + parts = [INTEGER_HEADER, CPUID_HELPER] + with pefile.PE(str(native_dll), fast_load=True) as pe: + for name in FOUR_ARG_EXPORTS: + ranges = function_ranges(pe, export_rva(pe, name)) + body = [ins for lo, hi in ranges for ins in region(pe, lo, hi)] + code = lower(body, ["rcx = arg_a; rdx = arg_b; r8 = arg_dst; r9 = arg_extra;"], {}, {}, {}) + parts.append( + f'extern "C" __declspec(dllexport) uint64_t {name}(uint64_t arg_a, uint64_t arg_b, uint64_t arg_dst, uint64_t arg_extra) {{\n{code}\n}}' + ) + for name in THREE_ARG_EXPORTS: + ranges = function_ranges(pe, export_rva(pe, name)) + body = [ins for lo, hi in ranges for ins in region(pe, lo, hi)] + code = lower(body, ["rcx = arg_a; rdx = arg_b; r8 = reinterpret_cast(arg_trace);"], {}, {}, {}) + parts.append( + f'extern "C" __declspec(dllexport) word {name}(word arg_a, word arg_b, word* arg_trace) {{\n{code}\n}}' + ) + text = mutate_control("\n".join(parts) + "\n", control) + output_cpp.write_text(text, encoding="utf-8") + + +def decode_check(hex_bytes: str) -> list: + body = list(Decoder(64, bytes.fromhex(hex_bytes), ip=0x1000)) + if any(i.is_invalid for i in body): + raise AssertionError(f"invalid instruction in test bytes {hex_bytes!r}: {body}") + return body + + +def check_rejections() -> None: + def attempt(hex_bytes: str, calls=None, host_ops=None): + body = decode_check(hex_bytes) + try: + lower(body, [], {}, calls or {}, {}, host_ops=host_ops) + except ValueError as exc: + return str(exc) + return None + + vcomiss = "c5 f8 2f c1" # vcomiss xmm0, xmm1 + vucomiss = "c5 f8 2e c1" # vucomiss xmm0, xmm1 + vcomisd = "c5 f9 2f c1" # vcomisd xmm0, xmm1 + vucomisd = "c5 f9 2e c1" # vucomisd xmm0, xmm1 + setp_al = "0f 9a c0" # setp al + setnp_al = "0f 9b c0" # setnp al + cmovp = "0f 4a c2" # cmovp eax, edx + cmovnp = "0f 4b c2" # cmovnp eax, edx + jp_self = "7a 00" # jp $+2 + ret = "c3" + + undef_msg = "reads PF, which no instruction defines on every path from the entry" + model_msg = "reads PF, which the integer lowering models only after" + indirect_msg = "PF consumers require known control-flow joins" + + rejected = { + "SETP AL at entry": (attempt(f"{setp_al} {ret}"), undef_msg), + "CMOVP EAX, EDX at entry": (attempt(f"{cmovp} {ret}"), undef_msg), + "JP at entry": (attempt(f"{jp_self} {ret}"), undef_msg), + "VCOMISS + ADD + SETP": (attempt(f"{vcomiss} 01 d0 {setp_al} {ret}"), model_msg), + "VUCOMISS + CMP + CMOVNP": (attempt(f"{vucomiss} 39 d0 {cmovnp} {ret}"), model_msg), + "VCOMISD + INC + JP": (attempt(f"{vcomisd} ff c0 {jp_self} {ret}"), model_msg), + "VUCOMISD + TEST32 + SETNP": (attempt(f"{vucomisd} 85 c0 {setnp_al} {ret}"), model_msg), + "VCOMISS + SHL + CMOVP": (attempt(f"{vcomiss} d1 e0 {cmovp} {ret}"), model_msg), + "VCOMISS + CALL + SETP": (attempt(f"{vcomiss} e8 00 00 00 00 {setp_al} {ret}", calls={0x1004: ";"}), undef_msg), + # JRCXZ (e3 04) skips VCOMISS (4 bytes) + JMP+2 (2 bytes -> e3 06) into ADD (01 d0). + "join VCOMISS path and ADD path": (attempt(f"e3 06 {vcomiss} eb 02 01 d0 {setp_al} {ret}"), model_msg), + # JRCXZ skips VCOMISS + JMP+2 into MOV EAX, EDX (leaves PF undefined). + "join VCOMISS path and MOV path": (attempt(f"e3 06 {vcomiss} eb 02 89 d0 {cmovp} {ret}"), undef_msg), + # VCOMISS + SETP + JMP RAX (indirect branch). + "indirect branch with PF consumer": (attempt(f"{vcomiss} {setp_al} ff e0"), indirect_msg), + # host_ops replacing a NOP invalidates tracked flags/PF. + "VCOMISS + host_ops + SETP": (attempt(f"{vcomiss} 90 {setp_al} {ret}", host_ops={0x1004: "rax = 1;"}), undef_msg), + } + for case, (msg, needle) in rejected.items(): + if msg is None or needle not in msg: + raise AssertionError(f"{case}: expected rejection with {needle!r}, got {msg!r}") + + accepted = { + "VCOMISS + MOV + LEA + VZEROUPPER + SETP": f"{vcomiss} 89 d0 8d 40 01 c5 f8 77 {setp_al} {ret}", + "join VCOMISS path and VUCOMISD path": f"e3 06 {vcomiss} eb 04 {vucomisd} {cmovp} {ret}", + "join VCOMISS path and TEST AL, AL path": f"e3 06 {vcomiss} eb 02 84 c0 {setnp_al} {ret}", + "VCOMISS + 8-bit AND CL, 1 + CMOVNP": f"{vcomiss} 80 e1 01 {cmovnp} {ret}", + } + for case, hex_bytes in accepted.items(): + body = decode_check(hex_bytes) + lower(body, [], {}, {}, {}) + + # Functions without PF consumers must not emit parity tracking. + no_pf_body = decode_check(f"{vcomiss} 0f 94 c0 {ret}") # vcomiss + sete al + ret + no_pf_cpp = lower(no_pf_body, [], {}, {}, {}) + if "parity" in no_pf_cpp: + raise AssertionError(f"unexpected parity tracking emitted without PF consumer:\n{no_pf_cpp}") + + print(f"rejected {len(rejected)} negative PF cases, accepted {len(accepted)} positive sequences, and preserved parity-free lowering") + + +def ref_cmp_bits(bits_a: int, bits_b: int, single: bool): + if single: + a = struct.unpack(" inf_bits or (bits_b & abs_mask) > inf_bits + if unordered: + pf, zf, cf = 1, 1, 1 + elif a == b: + pf, zf, cf = 0, 1, 0 + elif a < b: + pf, zf, cf = 0, 0, 1 + else: + pf, zf, cf = 0, 0, 0 + return bytes((pf, pf ^ 1, zf, cf, pf, pf ^ 1, 1 if (pf == 0 and zf == 1) else 0)) + + +def configure_lib(path: Path): + lib = ctypes.CDLL(str(path.resolve())) + for name in FOUR_ARG_EXPORTS: + fn = getattr(lib, name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64] + fn.restype = ctypes.c_uint64 + for name in THREE_ARG_EXPORTS: + fn = getattr(lib, name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.POINTER(ctypes.c_uint64)] + fn.restype = ctypes.c_uint64 + return lib + + +F32_VALUES = ( + ("neg_2.5", 0xC0200000), + ("neg_zero", 0x80000000), + ("pos_zero", 0x00000000), + ("subnormal", 0x00000001), + ("one", 0x3F800000), + ("two", 0x40000000), + ("neg_inf", 0xFF800000), + ("pos_inf", 0x7F800000), + ("qnan_pos", 0x7FC00000), + ("qnan_neg", 0xFFC01234), + ("snan_pos", 0x7F800001), + ("snan_neg", 0xFF801234), +) + +F64_VALUES = ( + ("neg_3.5", 0xC00C000000000000), + ("neg_zero", 0x8000000000000000), + ("pos_zero", 0x0000000000000000), + ("subnormal", 0x0000000000000001), + ("one", 0x3FF0000000000000), + ("two", 0x4000000000000000), + ("neg_inf", 0xFFF0000000000000), + ("pos_inf", 0x7FF0000000000000), + ("qnan_pos", 0x7FF8000000000000), + ("qnan_neg", 0xFFF8000000001234), + ("snan_pos", 0x7FF0000000000001), + ("snan_neg", 0xFFF0000000001234), +) + + +def check_cmov_faults(guard_path: Path, sides) -> int: + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.VirtualAlloc.restype = ctypes.c_void_p + kernel32.VirtualAlloc.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint32] + kernel32.VirtualProtect.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_void_p] + kernel32.VirtualFree.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32] + + guarded = ctypes.CDLL(str(guard_path.resolve())).guarded_call + guarded.argtypes = [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_uint64, + ctypes.POINTER(ctypes.c_uint64), ctypes.POINTER(ctypes.c_uint64)] + guarded.restype = ctypes.c_uint32 + + base = kernel32.VirtualAlloc(None, 2 * PAGE, 0x3000, 0x04) # MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE + if not base: + raise ctypes.WinError(ctypes.get_last_error()) + cases = 0 + try: + old = ctypes.c_uint32() + if not kernel32.VirtualProtect(base + PAGE, PAGE, 0x01, ctypes.byref(old)): # PAGE_NOACCESS + raise ctypes.WinError(ctypes.get_last_error()) + readable_ptr = base + PAGE - 4 + ctypes.c_uint32.from_address(readable_ptr).value = 0xFEDCBA98 + trace = (ctypes.c_uint64 * 4)(0, 0, 0, 0) + + pairs = ( + ("ordered_lt", 0x3F800000, 0x40000000, 0), + ("ordered_eq", 0x3F800000, 0x3F800000, 0), + ("unordered_qnan_a", 0x7FC00000, 0x3F800000, 1), + ("unordered_snan_b", 0x3F800000, 0x7F800001, 1), + ) + for pair_name, bits_a, bits_b, pf in pairs: + pair_buf = (ctypes.c_uint32 * 2)(bits_a, bits_b) + for fn_name, take_on_pf1 in (("cmovp_mem32", True), ("cmovnp_mem32", False)): + taken = (pf == 1) if take_on_pf1 else (pf == 0) + want_val = 0x00000000FEDCBA98 if taken else 0x0000000055667788 + for mem_label, mem_ptr, want_code in ( + ("readable", readable_ptr, 0), + ("page_noaccess", base + PAGE, ACCESS_VIOLATION), + ("null", 0, ACCESS_VIOLATION), + ): + for side_label, lib in sides: + fn = getattr(lib, fn_name) + res = ctypes.c_uint64(0xDEADDEADDEADDEAD) + code = guarded( + ctypes.cast(fn, ctypes.c_void_p), + ctypes.addressof(pair_buf), + mem_ptr, + trace, + ctypes.byref(res), + ) + if code != want_code: + raise AssertionError( + f"{side_label} {fn_name} ({pair_name}, {mem_label}): code={code:#x}, expected={want_code:#x}" + ) + if want_code == 0 and res.value != want_val: + raise AssertionError( + f"{side_label} {fn_name} ({pair_name}, {mem_label}): result={res.value:#018x}, expected={want_val:#018x}" + ) + cases += 1 + finally: + kernel32.VirtualFree(base, 0, 0x8000) # MEM_RELEASE + return cases + + +def check(guard_path: Path, native_path: Path, lifted_path: Path, o2_path: Path, *control_paths: Path) -> None: + check_rejections() + + lifted = configure_lib(lifted_path) + lifted.host_has_avx.restype = ctypes.c_uint32 + if not lifted.host_has_avx(): + print("host lacks AVX; skipping native differential check") + raise SystemExit(77) + + lifted_o2 = configure_lib(o2_path) + native = configure_lib(native_path) + sides = (("native", native), ("lifted", lifted), ("/O2", lifted_o2)) + + exchange = lifted.host_exchange_mxcsr + exchange.argtypes = [ctypes.c_uint32] + exchange.restype = ctypes.c_uint32 + saved_mxcsr = exchange(MXCSR_ALL_MASKED) + total_cases = 0 + out7 = (ctypes.c_ubyte * 7)() + out_join = (ctypes.c_ubyte * 16)() + out_cmov = (ctypes.c_uint64 * 6)() + + try: + # 1. All 4 scalar VEX compares (register and memory RHS), including qNaN/sNaN in each operand. + for fn_name in FLAG_EXPORTS: + single = "ss" in fn_name + vals = F32_VALUES if single else F64_VALUES + fmt = " CMOVP + SETP + JP). + join_inputs = ( + ("ordered", 0x3F800000, 0x40000000, 0x3FF0000000000000, 0x4000000000000000), + ("equal", 0x3F800000, 0x3F800000, 0x8000000000000000, 0x0000000000000000), + ("qnan0", 0x7FC00000, 0x3F800000, 0x7FF8000000000000, 0x3FF0000000000000), + ("snan1", 0x3F800000, 0x7F800001, 0x3FF0000000000000, 0x7FF0000000000001), + ) + for label, f_a, f_b, d_a, d_b in join_inputs: + buf_a = ctypes.create_string_buffer(struct.pack("(static_cast({operand(1)}))") elif (op in (M.CMOVE, M.CMOVNE, M.CMOVA, M.CMOVAE, M.CMOVB, M.CMOVBE) or + (parity and op in (M.CMOVP, M.CMOVNP)) or (x87_depth is None and op in (M.CMOVL, M.CMOVGE, M.CMOVLE, M.CMOVG, M.CMOVS, M.CMOVNS, M.CMOVO, M.CMOVNO))): cond = {M.CMOVE: "zero", M.CMOVNE: "!zero", M.CMOVA: "!carry && !zero", M.CMOVAE: "!carry", M.CMOVB: "carry", M.CMOVBE: "carry || zero", + M.CMOVP: "parity", M.CMOVNP: "!parity", M.CMOVL: "sign != overflow", M.CMOVGE: "sign == overflow", M.CMOVLE: "zero || (sign != overflow)", M.CMOVG: "!zero && (sign == overflow)", M.CMOVS: "sign", M.CMOVNS: "!sign", @@ -3024,9 +3033,11 @@ def p2_lane(sel, out_off): elif op == M.NOP or (op == M.XCHG and i.op0_register == i.op1_register == R.AX): stmt = ";" elif (op in (M.SETE, M.SETNE, M.SETA, M.SETAE, M.SETB, M.SETBE) or + (parity and op in (M.SETP, M.SETNP)) or (x87_depth is None and op in (M.SETL, M.SETGE, M.SETLE, M.SETG, M.SETS, M.SETNS, M.SETO, M.SETNO))): cond = {M.SETE: "zero", M.SETNE: "!zero", M.SETA: "!carry && !zero", M.SETAE: "!carry", M.SETB: "carry", M.SETBE: "carry || zero", + M.SETP: "parity", M.SETNP: "!parity", M.SETL: "sign != overflow", M.SETGE: "sign == overflow", M.SETLE: "zero || (sign != overflow)", M.SETG: "!zero && (sign == overflow)", M.SETS: "sign", M.SETNS: "!sign", diff --git a/tools/x87_lower.py b/tools/x87_lower.py index 0b952949a..2bf988581 100644 --- a/tools/x87_lower.py +++ b/tools/x87_lower.py @@ -386,7 +386,12 @@ def depths(body, exits, checked=None): # Instructions that put a function under the flag and status-word rules. -GATED = frozenset({*FCMOV, M.FNSTSW, M.SAHF, M.JP, M.JNP}) +GATED = frozenset({*FCMOV, M.FNSTSW, M.SAHF, M.JP, M.JNP, M.SETP, M.SETNP, M.CMOVP, M.CMOVNP}) +VEX_SCALAR_COMPARES = frozenset({M.VCOMISS, M.VUCOMISS, M.VCOMISD, M.VUCOMISD}) +PF_CLEARED = frozenset({ + M.RDRAND, M.RDSEED, M.PTEST, M.VPTEST, M.VTESTPS, M.VTESTPD, + M.PCMPESTRI, M.PCMPESTRM, M.PCMPISTRI, M.PCMPISTRM, +}) # The six status flags. FCMOV reads ZF and CF; DF is not tracked, because the Windows x64 calling @@ -439,9 +444,10 @@ def _flags_after(i, before): def assigns_parity(i): - """Whether the integer lowering sets PF for i: SAHF, the FCOMI family, and TEST and AND with an 8-bit - destination.""" - if i.mnemonic == M.SAHF or i.mnemonic in COMPARES: + """Whether the integer lowering sets PF for i: SAHF, the FCOMI family, the scalar VEX compares, + PF-clearing vector/entropy instructions, and TEST and AND with an 8-bit destination.""" + if (i.mnemonic == M.SAHF or i.mnemonic in COMPARES + or i.mnemonic in VEX_SCALAR_COMPARES or i.mnemonic in PF_CLEARED): return True if i.mnemonic not in (M.TEST, M.AND): return False @@ -486,8 +492,10 @@ def _ax_access(i): return read, written -def _after(i, s): +def _after(i, s, host_ops=None): """The state after i (the conditions it may raise are checked separately, in check_flags).""" + if host_ops and i.ip in host_ops: + return _State(0, 0, False, 0, 0xFFFF) op = i.mnemonic call = i.flow_control in (FlowControl.CALL, FlowControl.INDIRECT_CALL) flags = _flags_after(i, s.flags) @@ -536,7 +544,7 @@ def _successors(i): return successors -def states(body): +def states(body, host_ops=None): """The _State before each reachable instruction of body, from body[0], where no flag, PF model or condition bit is known and AX holds no status word. The integer lowering starts its flags as false, which is not what a native caller passes in, so a reader of an undefined flag would see that @@ -546,7 +554,7 @@ def states(body): work = [body[0].ip] while work: i = index[work.pop()] - after = _after(i, known[i.ip]) + after = _after(i, known[i.ip], host_ops) for target in _successors(i): if target in index: joined = after if target not in known else known[target].join(after) @@ -560,25 +568,27 @@ def _bits(mask): return f"{mask:#06x}" -def check_flags(body, exits): +def check_flags(body, exits, *, skip_lahf=False, host_ops=None): """Reject a read of an undefined status flag, a read of PF that the integer lowering does not model, and a reader of AX, or a point where RAX leaves the function, that sees a status-word bit not known.""" - known = states(body) + known = states(body, host_ops=host_ops) for i in body: s = known.get(i.ip) if s is None: continue # not reachable from the entry - missing = i.rflags_read & STATUS_FLAGS & ~s.flags - if missing: - names = " and ".join(name for name, bit in FLAG_NAMES if missing & bit) - if missing & s.tainted == missing: - raise ValueError(f"{i} at {i.ip:#x} reads {names}, which depends on a status-word bit that is not " - "known on every path from the entry") - raise ValueError(f"{i} at {i.ip:#x} reads {names}, which no instruction defines on every path from " - "the entry") - if i.rflags_read & F.PF and not s.parity: - raise ValueError(f"{i} at {i.ip:#x} reads PF, which the integer lowering models only after SAHF, " - "FCOMI, FCOMIP, FUCOMI, FUCOMIP and an 8-bit TEST or AND") + if not (skip_lahf and i.mnemonic == M.LAHF): + missing = i.rflags_read & STATUS_FLAGS & ~s.flags + if missing: + names = " and ".join(name for name, bit in FLAG_NAMES if missing & bit) + if missing & s.tainted == missing: + raise ValueError(f"{i} at {i.ip:#x} reads {names}, which depends on a status-word bit that is not " + "known on every path from the entry") + raise ValueError(f"{i} at {i.ip:#x} reads {names}, which no instruction defines on every path from " + "the entry") + if i.rflags_read & F.PF and not s.parity: + raise ValueError(f"{i} at {i.ip:#x} reads PF, which the integer lowering models only after SAHF, " + "FCOMI, FCOMIP, FUCOMI, FUCOMIP and an 8-bit TEST or AND, the scalar VEX compares, " + "or a PF-clearing instruction") unknown = 0xFFFF & ~s.ax if not unknown: continue From 209745a318d7a3cdf121641c4834eaeea7e37257 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 24 Nov 2026 03:20:31 +0000 Subject: [PATCH 004/775] shader: cover mesh amplification forms --- CMakeLists.txt | 7 + README.md | 1 + docs/experiments.md | 42 ++++++ docs/xcl-capability-matrix.md | 4 +- tests/desktop_gpu.h | 5 +- tests/mesh_amplification_refusal_check.py | 67 +++++++++ tests/mesh_amplified_check.py | 157 ++++++++++++++++++++++ tests/mesh_entry_draw.cpp | 82 ++++++++--- tests/offscreen_check.cpp | 11 ++ tests/pixel_aot_check.py | 8 +- tools/mesh_entry_aot.py | 33 +++++ 11 files changed, 392 insertions(+), 25 deletions(-) create mode 100644 tests/mesh_amplification_refusal_check.py create mode 100644 tests/mesh_amplified_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 5940ea04b..7daebafd8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4537,6 +4537,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/array_atomics_dxil_check.py" "${DXC_EXECUTABLE}" "${CMAKE_CURRENT_BINARY_DIR}/ProbeArrayAtomics.cso" "${CMAKE_SOURCE_DIR}/tests/gpu_alias_writes.hlsl" "${CMAKE_SOURCE_DIR}/src") + add_test(NAME mesh_amplification_refusal COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_amplification_refusal_check.py") + set_tests_properties(mesh_amplification_refusal PROPERTIES TIMEOUT 30) foreach(adapter IN ITEMS hardware warp) add_test(NAME mesh_pixel_pipeline_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_pixel_pipeline_check.py" "${DXC_EXECUTABLE}" @@ -4616,6 +4619,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/mesh_entry_check.py" draw-cvt-minmax "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(mesh_entry_cvt_minmax_draw_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME mesh_amplified_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_amplified_check.py" "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(mesh_amplified_draw_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME compute_store_aot_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 039a035c3..8d0a10ce1 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,7 @@ After the full [Windows build](#first-build), run one comparison from the reposi | [Publish RGBA8 textures from completed archive records](docs/experiments.md#publishing-a-texture-from-each-complete-archive-record) | `ctest --preset release --no-tests=error -R '^cpu_archive_texture_publication$' -V` | | [Draw each archive record through D3D12](docs/experiments.md#drawing-each-archive-record-through-d3d12) | `ctest --preset dev --no-tests=error -R '^cpu_archive_texture_gpu_warp$' -V` | | Indexed mesh draw on WARP | `ctest --preset dev --no-tests=error -R '^mesh_indexed_draw_warp$' -V` | +| [Amplification plus mesh pipeline on WARP](docs/experiments.md#amplification-and-mesh-pipeline-forms) | `ctest --preset dev --no-tests=error -R '^mesh_amplified_draw_warp$' -V` | | Textured mesh fallback at Shader Model 6.0 | `ctest --preset dev --no-tests=error -R '^mesh_textured_fallback_' -V` | | GPU-produced texture through the SM 6.0 mesh fallback | `ctest --preset dev --no-tests=error -R '^compute_mesh_texture_fallback_' -V` | | Compute shader buffer writes on WARP | `ctest --preset dev --no-tests=error -R '^compute_store_aot_warp$' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index cb1f528e0..054a4119f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2704,6 +2704,48 @@ reference index caused the comparison to fail. Tested on Windows build 26200.9974, RTX 4060 Laptop driver 32.0.16.1656 and WARP 10.0.26100.9818, with the debug layer enabled. +## Amplification and mesh pipeline forms + +`tests/mesh_amplified_check.py` builds an amplification shader (`as_6_5`) and a +mesh shader (`ms_6_5`) that reads its payload. `offscreen_check --mesh-amplified + ` creates one pipeline state with the AS, +MS and PS subobjects and issues `DispatchMesh(1,1,1)` for a single AS group. The +AS dispatches one mesh group and passes a depth word; the MS exports the same +80-byte trace as the translated mesh fixtures, and the 32x32 target compares all +1,024 RGBA pixels. A `--mesh-entry` draw with the same mesh body and no AS is the +positive control for the mesh-only form. + +The stale-payload control compiles the AS with 0.75 in place of 0.5. It must fail +`Mesh export trace mismatch` at the first differing depth byte (trace byte 26) +while every pixel still matches, which shows that the AS payload reaches the MS +and changes its exported vertex. The wrong-image control keeps the trace intact +and reports 1,024 pixel mismatches. WARP accepts +a mesh-only pipeline whose MS declares `in payload`, but the payload contents +are then undefined, so the fixture does not use that shape as a control. + +```powershell +ctest --preset dev --no-tests=error -R '^mesh_amplified_draw_' -V +ctest --preset dev --no-tests=error -R '^mesh_amplification_refusal$' -V +``` + +Both draws matched on Windows 10 Pro 26H2 build 26300.10075 with DXC +1.8.2502.11 (`10.0.26100.0`). On in-box WARP 10.0.26100.10068 (Microsoft Basic +Render Driver, vendor 1414, device 008c), the mesh-only pipeline reported +`mesh_pipeline_ms=0.659` and the AS+MS pipeline reported `1.092`. On the AMD +Radeon RX 9060 XT (vendor 1002, device 7590, driver 32.0.32029.2010), every +`_hardware` variant also passed; the full `^mesh_` filter ran 37/37 with no +failure. The debug layer was unavailable. A hardware target without a mesh +shader tier exits 77. + +The translator refuses the guest amplification stage by name. `require_mesh_stage` +checks both the PSV0 stage byte and the DXIL program kind before the mesh profile +checks, and stage 14 reports `Unsupported amplification stage: only the bounded +mesh stage is translated`. The accepted form remains one triangle-topology mesh +program with 128 threads, three vertices and one primitive in a single group. +Guest amplification code, a multi-group mesh dispatch, a translated mesh payload +and the meshlet command stream are not translated. The fixture above is source +built; it makes no console mesh-shader ABI claim. + ## Compute UAV stores from a native container `tools/compute_store_aot.py` accepts a local extracted DXBC compute container. It checks the stage in both the DXIL and PSV0 parts, the group dimensions, the FSSM v0x101 extent and termination, then decodes the gfx1013 instructions with LLVM. The store profile translates one or more non-overlapping raw UAV stores of one to four known 32-bit constant words per invocation, including constants loaded via `s_mov_b32`, `s_movk_i32`, and `v_mov_b32` register copies, along with `s_clause` hints and combined `lgkmcnt(0)`/`vmcnt(0)` waits. A test binding maps one four-word descriptor to u0. Its table pointer has a known low register and a zero high word. Scalar loads must complete before use. For an indexed store the caller also supplies the group-X register and byte stride, v0 carries local X, and the decoded shift and add must produce the dispatch-thread index. The tests bind in-range raw buffers with no swizzle, format conversion or out-of-range accesses. The original descriptor contents and dispatch configuration require separate evidence. diff --git a/docs/xcl-capability-matrix.md b/docs/xcl-capability-matrix.md index 0ac5a27e1..939d3123b 100644 --- a/docs/xcl-capability-matrix.md +++ b/docs/xcl-capability-matrix.md @@ -12,9 +12,9 @@ The XCL column describes public behaviour at the pin. It is not a local measurem | XGameRuntime | Provides GDK runtime services such as user, save, package and system calls. | None. | No XGameRuntime shim or source-built call fixture is checked in. | | D3D12.X device, root signatures and descriptor heaps | Creates the console device, accepts console root-signature flags and builds descriptor heaps through the returned device. | `desktop_root_signature`, `d3d12_xs_shim_exports`, `d3d12_xs_shim_serialize`, `d3d12_xs_shim_deserialize`, `d3d12_xs_shim_warp_root`, `d3d12x_descriptor_heap_warp`, `d3d12x_descriptor_table_warp` | Only the exported root-signature surface, device-creation entry and desktop descriptor semantics on the returned device are covered; console vtable slots, console descriptor layout, resource creation and the console command-list interface are not measured. | | D3D12.X command lists | Records and submits console compute and graphics lists, including PresentX. | No D3D12X list export. `d3d12x_compute_list_warp` records a desktop compute list through the XCL-08 device; `cpu_shim_compute_warp` and `cpu_shim_draw_warp` cover the separate desktop D3D12 path from PE entry. | No console command-list or PresentX interface; these fixtures do not establish one. | -| Shader translation | Translates console shader programs to desktop shaders across stages. | `pixel_aot_warp`, `pixel_aot_u32_from_f32_warp`, `compute_store_aot_warp`, `compute_store_aot_lds_qword_warp`, `mesh_entry_draw_warp`, `mesh_pixel_pipeline_warp` | Selected forms and stages are measured; no whole-pack translation rate is checked in. | +| Shader translation | Translates console shader programs to desktop shaders across stages. | `pixel_aot_warp`, `pixel_aot_u32_from_f32_warp`, `compute_store_aot_warp`, `compute_store_aot_lds_qword_warp`, `mesh_entry_draw_warp`, `mesh_pixel_pipeline_warp`, `mesh_amplified_draw_warp`, `mesh_amplification_refusal` | Selected forms and stages are measured; amplification is refused by name rather than translated; no whole-pack translation rate is checked in. | | Shader census and tools | Reports shader records, stages and unsupported forms. | `shader_metadata_census`, `compressed_scene_metadata`, `shader_metadata_controls` | Focused metadata probes exist; no checked-in whole-pack census. | -| Pipelines | Creates graphics and compute pipelines, including mesh combinations. | `pso_root_signature_warp`, `pso_readiness_check`, `mesh_pixel_pipeline_warp` | Selected desktop PSOs are measured; console pipeline creation and multi-stage combinations are not covered. | +| Pipelines | Creates graphics and compute pipelines, including mesh combinations. | `pso_root_signature_warp`, `pso_readiness_check`, `mesh_pixel_pipeline_warp`, `mesh_amplified_draw_warp` | Selected desktop PSOs are measured, including one AS+MS+PS pipeline; console pipeline creation and multi-group mesh dispatches are not covered. | | Textures | Handles console tiling, mip layouts and BC formats. | `bc7_block_reference`, `bc7_tile_swizzle`, `bc7_draw_warp`, `bcpack_prefix_and_mip_tail`, `bcpack_rans_symbols` | BC7 and BCPack paths are measured; full GFX10 tiling and other BC families are not checked in as one runtime path. | | Audio | Provides XAudio2 voices and console audio formats. | `audio_awc_metadata` | Metadata inventory only; no voice output or XMA/Opus decode path is measured. | | Media and BVH | Runs Bink, FidelityFX and BVH media paths. | `bvh_root_roundtrip_warp`, `bvh_differential_warp`, `ffx_pass26_lds_warp`, `cpu_aot_bink_heap`, `cpu_bink_frame_to_heap` | Selected Bink, FidelityFX and BVH fixtures pass; no end-to-end media path is checked in. | diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 8d4fe03ed..54505e573 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -36,7 +36,10 @@ struct MeshTextureProducers { bool check_mesh_entry_draw(ID3D12Device*, const char*, const char*, const char*, bool, MeshConstantBinding = MeshConstantBinding::root, MeshDrawMode = MeshDrawMode::color, - const MeshTextureProducers* = nullptr); + const MeshTextureProducers* = nullptr, + const char* amplification = nullptr); +bool check_mesh_amplified_draw(ID3D12Device*, const char* amplification, const char* mesh, + const char* pixel, const char* fixture); void check_mesh_fallback_draw(ID3D12Device* device, const char* compute, const char* vertex, const char* pixel, const char* fixture, MeshDrawMode mode = MeshDrawMode::color, const MeshTextureProducers* = nullptr); diff --git a/tests/mesh_amplification_refusal_check.py b/tests/mesh_amplification_refusal_check.py new file mode 100644 index 000000000..b0df5ab94 --- /dev/null +++ b/tests/mesh_amplification_refusal_check.py @@ -0,0 +1,67 @@ +"""Refuse a guest amplification stage by name, and keep the mesh stage accepted.""" + +from pathlib import Path +import struct +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from mesh_entry_aot import require_mesh_stage, translate # noqa: E402 +from pixel_aot import _read_named_container, parts # noqa: E402 +from pixel_aot_check import envelope # noqa: E402 + +AMPLIFICATION = ( + "Unsupported amplification stage: only the bounded mesh stage is translated" +) +COMPUTE = "Unsupported compute stage: only the bounded mesh stage is translated" + + +def container(stage): + record = envelope( + bytes.fromhex("00009fbf"), + b"probe", + compute_width=128, + mesh_limits=(3, 1) if stage == 13 else None, + shader_stage=stage, + ) + return _read_named_container(record, len(b"probe") + 2) + + +def refused(function, expected, *args): + try: + function(*args) + except ValueError as exc: + if str(exc) != expected: + raise AssertionError(f"expected {expected!r}, got {exc}") from exc + return + raise AssertionError(f"{function.__name__} accepted its input") + + +def stage_chunks(psv_stage, kind): + psv = bytearray(52) + psv[28] = psv_stage + program = bytearray(4) + struct.pack_into(" ") + raise SystemExit(main(*sys.argv[1:])) diff --git a/tests/mesh_entry_draw.cpp b/tests/mesh_entry_draw.cpp index 6f8c24349..4e5d2d49a 100644 --- a/tests/mesh_entry_draw.cpp +++ b/tests/mesh_entry_draw.cpp @@ -53,6 +53,19 @@ struct MeshPipeline { Field topology; }; +// An empty AS subobject is invalid, so an amplified pipeline keeps its own stream. +struct MeshAmplifiedPipeline { + Field root; + Field as; + Field ms; + Field ps; + Field formats; + Field raster; + Field depth; + Field depth_format; + Field topology; +}; + ComPtr fallback_draw_pipeline(ID3D12Device* device, ID3D12RootSignature* root, D3D12_SHADER_BYTECODE vs, D3D12_SHADER_BYTECODE ps, const D3D12_DEPTH_STENCIL_DESC& depth, DXGI_FORMAT depth_format) @@ -92,7 +105,7 @@ ComPtr create_draw_root(ID3D12Device* device, const D3D12_R bool check_mesh_draw(ID3D12Device* device, const char* first, const char* second, const char* fixture, bool vertices, MeshConstantBinding binding, const char* fallback_vertex, MeshDrawMode mode, - const MeshTextureProducers* producers) + const MeshTextureProducers* producers, const char* amplification) { const bool fallback = fallback_vertex != nullptr; if (!fallback) { @@ -196,24 +209,46 @@ bool check_mesh_draw(ID3D12Device* device, const char* first, const char* second desc.CS = {shader.data(), shader.size()}; check(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&compute_pipeline)), "Create mesh export compute pipeline"); } else { - MeshPipeline stream; - stream.root.value = root.Get(); - stream.ms.value = {shader.data(), shader.size()}; - stream.ps.value = ps; - stream.formats.value.NumRenderTargets = 1; - stream.formats.value.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - stream.raster.value.FillMode = D3D12_FILL_MODE_SOLID; - stream.raster.value.CullMode = D3D12_CULL_MODE_NONE; - stream.raster.value.DepthClipEnable = TRUE; - stream.depth.value = depth_state; - stream.depth_format.value = depth_format; - stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; ComPtr device2; check(device->QueryInterface(IID_PPV_ARGS(&device2)), "Query mesh pipeline device"); + // A source-built AS dispatches the mesh groups and passes the payload this + // fixture reads. Mesh-only pipelines keep the AS subobject out of their stream. + const auto amplification_shader = amplification ? read_bytes(amplification) : std::vector{}; // tools/mesh_od_pipeline.py reads this line to separate pipeline creation from the process time. const auto pipeline_start = std::chrono::steady_clock::now(); - const HRESULT created = device2->CreatePipelineState(&desc, IID_PPV_ARGS(&pipeline)); + HRESULT created; + if (amplification) { + MeshAmplifiedPipeline stream; + stream.root.value = root.Get(); + stream.as.value = {amplification_shader.data(), amplification_shader.size()}; + stream.ms.value = {shader.data(), shader.size()}; + stream.ps.value = ps; + stream.formats.value.NumRenderTargets = 1; + stream.formats.value.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + stream.raster.value.FillMode = D3D12_FILL_MODE_SOLID; + stream.raster.value.CullMode = D3D12_CULL_MODE_NONE; + stream.raster.value.DepthClipEnable = TRUE; + stream.depth.value = depth_state; + stream.depth_format.value = depth_format; + stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + created = device2->CreatePipelineState(&desc, IID_PPV_ARGS(&pipeline)); + } else { + MeshPipeline stream; + stream.root.value = root.Get(); + stream.ms.value = {shader.data(), shader.size()}; + stream.ps.value = ps; + stream.formats.value.NumRenderTargets = 1; + stream.formats.value.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + stream.raster.value.FillMode = D3D12_FILL_MODE_SOLID; + stream.raster.value.CullMode = D3D12_CULL_MODE_NONE; + stream.raster.value.DepthClipEnable = TRUE; + stream.depth.value = depth_state; + stream.depth_format.value = depth_format; + stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + created = device2->CreatePipelineState(&desc, IID_PPV_ARGS(&pipeline)); + } const std::chrono::duration pipeline_time = std::chrono::steady_clock::now() - pipeline_start; std::printf("mesh_pipeline_ms=%.3f\n", pipeline_time.count()); std::fflush(stdout); // Keep the line if the process dies after pipeline creation. @@ -455,7 +490,7 @@ bool check_mesh_draw(ID3D12Device* device, const char* first, const char* second const auto* trace_end = reference + trace_bytes; const auto* first_bad = std::mismatch(reference, trace_end, rows + size).first; const bool trace_ok = first_bad == trace_end; - if (fallback || depth_pair) { + if (fallback || depth_pair || !trace_ok) { std::printf("mesh_exports bytes=%u matched=%d\n", trace_bytes, trace_ok ? 1 : 0); if (!trace_ok) std::printf("first_mesh_export_mismatch_byte=%td\n", first_bad - reference); } @@ -489,14 +524,23 @@ bool check_mesh_draw(ID3D12Device* device, const char* first, const char* second bool check_mesh_entry_draw(ID3D12Device* device, const char* mesh, const char* pixel, const char* fixture, bool vertices, MeshConstantBinding binding, MeshDrawMode mode, - const MeshTextureProducers* producers) + const MeshTextureProducers* producers, const char* amplification) +{ + return check_mesh_draw(device, mesh, pixel, fixture, vertices, binding, nullptr, mode, producers, + amplification); +} + +bool check_mesh_amplified_draw(ID3D12Device* device, const char* amplification, const char* mesh, + const char* pixel, const char* fixture) { - return check_mesh_draw(device, mesh, pixel, fixture, vertices, binding, nullptr, mode, producers); + return check_mesh_entry_draw(device, mesh, pixel, fixture, false, MeshConstantBinding::root, + MeshDrawMode::color, nullptr, amplification); } void check_mesh_fallback_draw(ID3D12Device* device, const char* compute, const char* vertex, const char* pixel, const char* fixture, MeshDrawMode mode, const MeshTextureProducers* producers) { - check_mesh_draw(device, compute, pixel, fixture, true, MeshConstantBinding::root, vertex, mode, producers); + check_mesh_draw(device, compute, pixel, fixture, true, MeshConstantBinding::root, vertex, mode, producers, + nullptr); } diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 6b6a23c35..6d2801cc7 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -754,6 +754,12 @@ OperationResult run_mesh_entry(const OperationContext& ctx) return skip_if_false(check_mesh_entry_draw(ctx.device, ctx.argv[3], ctx.argv[4], ctx.argv[5], false, binding)); } +OperationResult run_mesh_amplified(const OperationContext& ctx) +{ + return skip_if_false(check_mesh_amplified_draw(ctx.device, ctx.argv[3], ctx.argv[4], ctx.argv[5], + ctx.argv[6])); +} + OperationResult run_mesh_indexed(const OperationContext& ctx) { return skip_if_false(check_mesh_entry_draw(ctx.device, ctx.argv[3], ctx.argv[4], ctx.argv[5], true)); @@ -1131,6 +1137,7 @@ const OperationSpec kOperations[] = { {"--depth-mask", 6, 6, nullptr, kNoGate, run_depth_mask}, {"--depth-mask-swapped", 6, 6, nullptr, kNoGate, run_depth_mask_swapped}, {"--mesh-entry", 6, 7, validate_mesh_entry_args, kNoGate, run_mesh_entry}, + {"--mesh-amplified", 7, 7, nullptr, kNoGate, run_mesh_amplified}, {"--mesh-indexed", 6, 6, nullptr, kNoGate, run_mesh_indexed}, {"--mesh-indexed-fallback", 7, 7, nullptr, kGateSm60MeshFallback, run_mesh_indexed_fallback}, {"--mesh-textured-fallback", 7, 7, nullptr, kGateSm60MeshFallback, run_mesh_textured_fallback}, @@ -1368,6 +1375,10 @@ int run_self_test() "Unknown GPU operation or invalid arguments: --check-pixel")) return 1; if (!check_cli({"offscreen_check", "warp", "--mesh-entry", "a", "b", "c", "invalid"}, CliAction::usage_error, "Unknown GPU operation or invalid arguments: --mesh-entry")) return 1; + if (!check_cli({"offscreen_check", "warp", "--mesh-amplified", "as", "ms", "ps"}, CliAction::usage_error, + "Unknown GPU operation or invalid arguments: --mesh-amplified")) return 1; + if (!check_cli({"offscreen_check", "warp", "--mesh-amplified", "as", "ms", "ps", "fixture"}, + CliAction::operation)) return 1; if (!check_cli({"offscreen_check", "warp", "--mesh-indexed-fallback", "cs", "vs", "ps"}, CliAction::usage_error, "Unknown GPU operation or invalid arguments: --mesh-indexed-fallback")) return 1; if (!check_cli({"offscreen_check", "warp", "--mesh-depth-pair-fallback", "cs", "vs", "ps"}, CliAction::usage_error, diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index a444db2d1..cf4c9ba82 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -195,7 +195,7 @@ def shader_record(blob: bytes, name: bytes) -> bytes: def envelope(code: bytes, name: bytes = b"fixture", *, private_data: bytes | None = None, directory_end=None, - compute_width=None, mesh_limits=None) -> bytes: + compute_width=None, mesh_limits=None, shader_stage=None) -> bytes: program_start = 288 if directory_end is not None else 256 image = bytearray(program_start) + code image[:4] = b"FSSM" @@ -209,12 +209,14 @@ def envelope(code: bytes, name: bytes = b"fixture", *, private_data: bytes | Non program = (bytes(24) + b"XDAT" + struct.pack("= 4 else None + for stage in (psv[28] if len(psv) > 28 else None, kind): + if stage == 13: + continue + if stage == 14: + raise ValueError( + "Unsupported amplification stage: only the bounded mesh stage is translated" + ) + if stage is not None: + name = STAGE_NAMES.get(stage, f"stage {stage}") + raise ValueError( + f"Unsupported {name} stage: only the bounded mesh stage is translated" + ) + + def translate(blob, geometry, library, vertex_header=None, *, compute_fallback=False): chunks = parts(blob) + require_mesh_stage(chunks) p = chunks[b"PSV0"] if ( len(p) < 52 From f2082414689a5d9413fa912899d5f71bc212cf53 Mon Sep 17 00:00:00 2001 From: Maxim Trusov <146969829+Maxim-Root@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:20:02 +0300 Subject: [PATCH 005/775] cpu: start the load-config /guard:cf fixtures with an explicit CFG policy cpu_native_load_config_callback asserted that Windows replaces both guard slots of every /guard:cf image. A child inherits the host's CFG setting, so with system CFG off the loader keeps the image's own slots and the check failed in the native cfg_record run, before reaching pe_map. Start cfg_record and cfg_invalid with PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY: CFG always on for the existing assertions, and CFG always off as a negative control that must match the record and invalid images linked without /guard:cf. Each child's EnableControlFlowGuard bit, read from its handle after exit, must match the requested policy. Co-Authored-By: Claude Opus 5.5 --- tests/cpu/load_config_callback_check.py | 137 ++++++++++++++++++++++-- 1 file changed, 128 insertions(+), 9 deletions(-) diff --git a/tests/cpu/load_config_callback_check.py b/tests/cpu/load_config_callback_check.py index 82bb89d69..bf7f6dc32 100644 --- a/tests/cpu/load_config_callback_check.py +++ b/tests/cpu/load_config_callback_check.py @@ -16,10 +16,15 @@ hold the relocated in-image targets on read-only pages. Windows replaces both slots of a /guard:cf image and ends a call to the invalid target before it writes -output. pe_map currently does not implement CFG: it keeps the image's own slots, so the valid callback runs -without the slot bits and the invalid target runs. The unchecked invalid result is recorded as an -observation. The test also accepts an explicit unsupported-CFG diagnostic before dispatch. An unrelated -load failure or a missing output record does not establish CFG behavior. +output, when CFG is enforced for the process. A child inherits the host's CFG setting, and with system CFG +off the loader keeps the image's own slots. The two /guard:cf images are therefore started with an explicit +per-process policy: CFG always on for the assertions above, and CFG always off as a negative control that +must give the result of the same objects linked without /guard:cf. Each child's effective +EnableControlFlowGuard bit is checked against the requested policy. pe_map currently does not implement CFG: +it keeps the image's own slots, so the valid callback runs without the slot bits and the invalid target +runs. The unchecked invalid result is recorded as an observation. The test also accepts an explicit +unsupported-CFG diagnostic before dispatch. An unrelated load failure or a missing output record does not +establish CFG behavior. """ import ctypes from ctypes import wintypes @@ -43,6 +48,103 @@ CF_INSTRUMENTED, CF_TABLE = 0x100, 0x400 # IMAGE_GUARD_CF_INSTRUMENTED, IMAGE_GUARD_CF_FUNCTION_TABLE_PRESENT SLOT_BITS = 0x30000 PAGE_READONLY = 0x02 +# PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_ON / _ALWAYS_OFF +CFG_POLICY = {"on": 1 << 40, "off": 2 << 40} + + +class StartupInfoEx(ctypes.Structure): + _fields_ = ([("cb", wintypes.DWORD), ("reserved", wintypes.LPWSTR), ("desktop", wintypes.LPWSTR), + ("title", wintypes.LPWSTR)] + + [(field, wintypes.DWORD) for field in ("x", "y", "x_size", "y_size", "x_chars", "y_chars", + "fill", "flags")] + + [("show", wintypes.WORD), ("reserved2_size", wintypes.WORD), ("reserved2", ctypes.c_void_p), + ("stdin", wintypes.HANDLE), ("stdout", wintypes.HANDLE), ("stderr", wintypes.HANDLE), + ("attributes", ctypes.c_void_p)]) + + +class ProcessInformation(ctypes.Structure): + _fields_ = [("process", wintypes.HANDLE), ("thread", wintypes.HANDLE), ("pid", wintypes.DWORD), + ("tid", wintypes.DWORD)] + + +class SecurityAttributes(ctypes.Structure): + _fields_ = [("length", wintypes.DWORD), ("descriptor", ctypes.c_void_p), ("inherit", wintypes.BOOL)] + + +def launch_cfg(image, policy, timeout=30): + """Start image under the Windows loader with an explicit per-process CFG policy ("on" or "off"). + + A /guard:cf image otherwise inherits the host's CFG setting, and with system CFG off the loader keeps the + image's own slots. The child's effective EnableControlFlowGuard bit is read from its handle after it ends. + stdin is NUL; stdout and stderr go to files beside the image. + """ + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.CreateFileW.restype = wintypes.HANDLE + kernel.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE] + kernel.InitializeProcThreadAttributeList.argtypes = [ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, + ctypes.POINTER(ctypes.c_size_t)] + kernel.UpdateProcThreadAttribute.argtypes = [ctypes.c_void_p, wintypes.DWORD, ctypes.c_size_t, ctypes.c_void_p, + ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p] + kernel.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p] + kernel.CreateProcessW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p, + wintypes.BOOL, wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR, + ctypes.c_void_p, ctypes.POINTER(ProcessInformation)] + kernel.GetProcessMitigationPolicy.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t] + kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD] + kernel.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT] + kernel.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)] + kernel.CloseHandle.argtypes = [wintypes.HANDLE] + + image = Path(image) + paths = {stream: image.with_name(f"{image.stem}.{policy}.{stream}") for stream in ("stdout", "stderr")} + inherit = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True) + handles = [kernel.CreateFileW("NUL", 0x80000000, 3, ctypes.byref(inherit), 3, 0x80, None)] # GENERIC_READ + handles += [kernel.CreateFileW(str(paths[stream]), 0x40000000, 1, ctypes.byref(inherit), 2, 0x80, None) + for stream in ("stdout", "stderr")] # GENERIC_WRITE, CREATE_ALWAYS + if any(handle in (None, wintypes.HANDLE(-1).value) for handle in handles): + error = ctypes.WinError(ctypes.get_last_error()) + for handle in handles: + if handle not in (None, wintypes.HANDLE(-1).value): + kernel.CloseHandle(handle) + raise error + size = ctypes.c_size_t() + kernel.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size)) + attributes = ctypes.create_string_buffer(size.value) + value = ctypes.c_uint64(CFG_POLICY[policy]) + info, process = StartupInfoEx(), ProcessInformation() + info.cb, info.flags = ctypes.sizeof(info), 0x100 # STARTF_USESTDHANDLES + info.stdin, info.stdout, info.stderr = handles + try: + if not kernel.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)): + raise ctypes.WinError(ctypes.get_last_error()) + try: + if not kernel.UpdateProcThreadAttribute(attributes, 0, 0x20007, ctypes.byref(value), 8, None, None): + raise ctypes.WinError(ctypes.get_last_error()) # PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY + info.attributes = ctypes.addressof(attributes) + # EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW; the parent's error mode is inherited. + if not kernel.CreateProcessW(str(image), None, None, None, True, 0x00080000 | 0x08000000, None, + str(image.parent), ctypes.byref(info), ctypes.byref(process)): + raise ctypes.WinError(ctypes.get_last_error()) + finally: + kernel.DeleteProcThreadAttributeList(attributes) + finally: + for handle in handles: + kernel.CloseHandle(handle) + try: + signaled = kernel.WaitForSingleObject(process.process, timeout * 1000) == 0 + if not signaled: + kernel.TerminateProcess(process.process, 1) + kernel.WaitForSingleObject(process.process, 5000) + code, flags = wintypes.DWORD(), wintypes.DWORD() + kernel.GetExitCodeProcess(process.process, ctypes.byref(code)) + if not kernel.GetProcessMitigationPolicy(process.process, 7, ctypes.byref(flags), 4): + raise ctypes.WinError(ctypes.get_last_error()) # ProcessControlFlowGuardPolicy + finally: + kernel.CloseHandle(process.thread) + kernel.CloseHandle(process.process) + return {"process_signaled": signaled, "code": code.value, "cfg": bool(flags.value & 1), + **{stream: {"bytes": path.read_bytes()} for stream, path in paths.items()}} def words(a, b, c, calls, d): @@ -191,9 +293,19 @@ def main(mapper_path, io, *images): "other": (0x99, words(0x22, 0x11, 0x33, 1, marker)), "invalid": (0x77, words(0, 0, 0, 0, 0)), } - row = launch([staged], b"", timeout=30) - if not row["process_signaled"]: - raise AssertionError(f"{name}: Windows launch did not end: {row}") + if name.startswith("cfg_"): + row, control = launch_cfg(staged, "on"), launch_cfg(staged, "off") + for policy, launched in (("on", row), ("off", control)): + if not launched["process_signaled"]: + raise AssertionError(f"{name}: Windows launch with CFG {policy} did not end: {launched}") + if launched["cfg"] != (policy == "on"): + raise AssertionError(f"{name}: requested CFG {policy}, but the child reports " + f"EnableControlFlowGuard={int(launched['cfg'])}") + uncontrolled = (control["code"], trace(control["stderr"]["bytes"], control["stdout"]["bytes"])) + else: + row = launch([staged], b"", timeout=30) + if not row["process_signaled"]: + raise AssertionError(f"{name}: Windows launch did not end: {row}") native = (row["code"], trace(row["stderr"]["bytes"], row["stdout"]["bytes"])) result, out, err = mapped(mapper_path, staged, staged_io, temp) started = result["status"] == STATUS["ok"] and result.get("started") == 1 @@ -207,7 +319,14 @@ def main(mapper_path, io, *images): observed[name] = native, mapped_row base = name.removeprefix("cfg_") - note = "mapped slots read-only and relocated" + note, control_note = "mapped slots read-only and relocated", "" + if name.startswith("cfg_"): + # Negative control: without CFG the loader keeps the image's own slots, so the /guard:cf + # image behaves like the same objects linked without /guard:cf. + if uncontrolled != expected[base]: + raise AssertionError(f"{name}: Windows with CFG off {uncontrolled}, expected the {base} " + f"result {expected[base]}") + control_note = f"; Windows with CFG off {show(uncontrolled)} (same as {base})" if name in expected: if native != expected[name] or mapped_row != expected[name]: raise AssertionError(f"{name}: Windows {native}, pe_map {mapped_row}, expected {expected[name]}") @@ -229,7 +348,7 @@ def main(mapper_path, io, *images): raise AssertionError(f"{name}: pe_map {mapped_row}, status {result['status']}, " f"expected the current observation or an explicit CFG refusal: {result}") shown = show(mapped_row) if mapped_row is not None else "not started" - print(f"{name}: Windows {show(native)}; pe_map {shown}; {note}") + print(f"{name}: Windows {show(native)}; pe_map {shown}; {note}{control_note}") if observed["other"][0] == observed["record"][0]: raise AssertionError("the control binding was not distinguished") From 818181369f3e59f8ab1d7fd2a1453dec0f604e1a Mon Sep 17 00:00:00 2001 From: Maxim Trusov <146969829+Maxim-Root@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:57:56 +0300 Subject: [PATCH 006/775] cpu: limit the CFG-policy child to its own handles and record a hung launch Review follow-ups for launch_cfg in load_config_callback_check.py: - pass the three standard handles through PROC_THREAD_ATTRIBUTE_HANDLE_LIST so the child no longer inherits every inheritable handle of the test; - read the CreateFileW error right after the failing call, so a later successful open cannot replace it; - wait 15 s per launch instead of 30 s, so the four policy launches stay well inside the test's 120 s CTest timeout, and record the child's live threads before terminating a launch that did not end. Co-Authored-By: Claude Opus 5.5 --- tests/cpu/load_config_callback_check.py | 41 +++++++++++++++---------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/tests/cpu/load_config_callback_check.py b/tests/cpu/load_config_callback_check.py index bf7f6dc32..3862ba352 100644 --- a/tests/cpu/load_config_callback_check.py +++ b/tests/cpu/load_config_callback_check.py @@ -39,7 +39,7 @@ import pefile -from exe_process import launch +from exe_process import launch, thread_ids from native_map_check import Mapper, STATUS IO = "cpu_exe_io.dll" @@ -71,12 +71,14 @@ class SecurityAttributes(ctypes.Structure): _fields_ = [("length", wintypes.DWORD), ("descriptor", ctypes.c_void_p), ("inherit", wintypes.BOOL)] -def launch_cfg(image, policy, timeout=30): +def launch_cfg(image, policy, timeout=15): """Start image under the Windows loader with an explicit per-process CFG policy ("on" or "off"). A /guard:cf image otherwise inherits the host's CFG setting, and with system CFG off the loader keeps the image's own slots. The child's effective EnableControlFlowGuard bit is read from its handle after it ends. - stdin is NUL; stdout and stderr go to files beside the image. + stdin is NUL; stdout and stderr go to files beside the image. The child inherits only these three handles. + The four launches together stay well inside the test's CTest timeout; a launch that does not end records + the child's live threads before it is terminated. """ kernel = ctypes.WinDLL("kernel32", use_last_error=True) kernel.CreateFileW.restype = wintypes.HANDLE @@ -99,28 +101,33 @@ def launch_cfg(image, policy, timeout=30): image = Path(image) paths = {stream: image.with_name(f"{image.stem}.{policy}.{stream}") for stream in ("stdout", "stderr")} inherit = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True) - handles = [kernel.CreateFileW("NUL", 0x80000000, 3, ctypes.byref(inherit), 3, 0x80, None)] # GENERIC_READ - handles += [kernel.CreateFileW(str(paths[stream]), 0x40000000, 1, ctypes.byref(inherit), 2, 0x80, None) - for stream in ("stdout", "stderr")] # GENERIC_WRITE, CREATE_ALWAYS - if any(handle in (None, wintypes.HANDLE(-1).value) for handle in handles): - error = ctypes.WinError(ctypes.get_last_error()) - for handle in handles: - if handle not in (None, wintypes.HANDLE(-1).value): - kernel.CloseHandle(handle) - raise error + opens = [("NUL", 0x80000000, 3, 3)] + [(str(paths[stream]), 0x40000000, 1, 2) for stream in ("stdout", "stderr")] + handles = [] + for name, access, share, disposition in opens: # GENERIC_READ OPEN_EXISTING, GENERIC_WRITE CREATE_ALWAYS + handle = kernel.CreateFileW(name, access, share, ctypes.byref(inherit), disposition, 0x80, None) + if handle in (None, wintypes.HANDLE(-1).value): + error = ctypes.WinError(ctypes.get_last_error()) # read before any other call can replace it + for opened in handles: + kernel.CloseHandle(opened) + raise OSError(f"opening {name} for the child: {error}") + handles.append(handle) size = ctypes.c_size_t() - kernel.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size)) + kernel.InitializeProcThreadAttributeList(None, 2, 0, ctypes.byref(size)) attributes = ctypes.create_string_buffer(size.value) value = ctypes.c_uint64(CFG_POLICY[policy]) + inherited = (wintypes.HANDLE * len(handles))(*handles) info, process = StartupInfoEx(), ProcessInformation() info.cb, info.flags = ctypes.sizeof(info), 0x100 # STARTF_USESTDHANDLES info.stdin, info.stdout, info.stderr = handles try: - if not kernel.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)): + if not kernel.InitializeProcThreadAttributeList(attributes, 2, 0, ctypes.byref(size)): raise ctypes.WinError(ctypes.get_last_error()) try: if not kernel.UpdateProcThreadAttribute(attributes, 0, 0x20007, ctypes.byref(value), 8, None, None): raise ctypes.WinError(ctypes.get_last_error()) # PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY + if not kernel.UpdateProcThreadAttribute(attributes, 0, 0x20002, inherited, ctypes.sizeof(inherited), + None, None): + raise ctypes.WinError(ctypes.get_last_error()) # PROC_THREAD_ATTRIBUTE_HANDLE_LIST info.attributes = ctypes.addressof(attributes) # EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW; the parent's error mode is inherited. if not kernel.CreateProcessW(str(image), None, None, None, True, 0x00080000 | 0x08000000, None, @@ -131,9 +138,11 @@ def launch_cfg(image, policy, timeout=30): finally: for handle in handles: kernel.CloseHandle(handle) + live_threads = None try: signaled = kernel.WaitForSingleObject(process.process, timeout * 1000) == 0 if not signaled: + live_threads = thread_ids(process.pid) kernel.TerminateProcess(process.process, 1) kernel.WaitForSingleObject(process.process, 5000) code, flags = wintypes.DWORD(), wintypes.DWORD() @@ -143,8 +152,8 @@ def launch_cfg(image, policy, timeout=30): finally: kernel.CloseHandle(process.thread) kernel.CloseHandle(process.process) - return {"process_signaled": signaled, "code": code.value, "cfg": bool(flags.value & 1), - **{stream: {"bytes": path.read_bytes()} for stream, path in paths.items()}} + return {"process_signaled": signaled, "code": code.value, "cfg": bool(flags.value & 1), "pid": process.pid, + "live_threads": live_threads, **{stream: {"bytes": path.read_bytes()} for stream, path in paths.items()}} def words(a, b, c, calls, d): From 06395b06b9864d11466e983113467da83d876861 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 11:36:39 +0100 Subject: [PATCH 007/775] cpu: restore the compacted XSAVE format in XRSTOR xrstor and xrstor64 now accept a header with XCOMP_BV[63] set, the layout xsavec writes. XCOMP_BV may list only x87, SSE and AVX, XSTATE_BV must be a subset of it and header bytes [528..575] must be zero, else #GP before any state changes. A requested component restores when XSTATE_BV and XCOMP_BV both list it and is initialized otherwise. MXCSR follows the SSE component in this format: loaded when RFBM[1] and XSTATE_BV[1] are set, reset to 0x1F80 when only RFBM[1] is set, untouched when RFBM[1] is clear. The standard format is unchanged. The rules were measured on a native AMD host; native fixtures are gated on CPUID.(0DH,1):EAX[1]. The prelude also gains the store64 helper that the lowering of a GPR store to memory already referenced but never defined. --- CMakeLists.txt | 7 +- docs/experiments.md | 51 ++++- tests/cpu/xsave_state.asm | 147 ++++++++++++- tests/cpu/xsave_state.def | 6 + tests/cpu/xsave_state_check.py | 387 +++++++++++++++++++++++++++++++-- tools/cpu_xsave_aot.py | 73 ++++++- 6 files changed, 642 insertions(+), 29 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 690289c07..066a925a7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2263,12 +2263,15 @@ if(EXISTS "${INTAKE_PYTHON}") "op_discarded_read,op_xrstor64_xsavec,op_xrstor64_xsavec64," "op_xrstor64_xsavec64_sse,op_xrstor64_xsavec64_x87_avx,op_xsavec64_dynmask," "op_xrstor64_xsaveopt,op_xrstor64_xsaveopt64,op_xrstor64_xsaveopt64_sse," - "op_xrstor64_xsaveopt64_x87_avx,op_xrstor64_xsaveopt64_avx,op_xsaveopt64_dynmask") + "op_xrstor64_xsaveopt64_x87_avx,op_xrstor64_xsaveopt64_avx,op_xsaveopt64_dynmask," + "op_xsavec_xrstor_all,op_xsavec_xrstor_x87_avx,op_xsavec_xrstor_x87_sse," + "op_xsavec_xrstor_avx_only,op_xsavec_xrstor_sse_only,op_xrstor64_compacted_dynmask") string(CONCAT cpu_xsave_state_original_exports ${cpu_xsave_state_original_exports}) set(cpu_xsave_state_altered_exports "op_xrstor64_xsave64,op_xrstor_xsave64,op_xrstor64_disp,op_pipeline," "op_xrstor64_xsavec64,op_xrstor64_xsavec64_sse," - "op_xrstor64_xsaveopt64,op_xrstor64_xsaveopt64_sse") + "op_xrstor64_xsaveopt64,op_xrstor64_xsaveopt64_sse," + "op_xsavec_xrstor_all,op_xsavec_xrstor_avx_only") string(CONCAT cpu_xsave_state_altered_exports ${cpu_xsave_state_altered_exports}) foreach(variant IN ITEMS original altered) cpu_asm_fixture(cpu_xsave_state_${variant} xsave_state) diff --git a/docs/experiments.md b/docs/experiments.md index 3be04deb5..26e8f0db0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1658,7 +1658,8 @@ group `XSAVE`: (`EDX == 0` and `(EAX & ~7) == 0`); raise `#GP` before mutating state on non-zero `XCOMP_BV`, non-zero reserved header bytes `[528..535]`, `(XSTATE_BV & ~7) != 0`, or `(RFBM & 6) != 0` with invalid `MXCSR & ~MXCSR_MASK`; restore or initialize each - requested component and update `XINUSE[2:0]` + requested component and update `XINUSE[2:0]`. A header with `XCOMP_BV[63]` set selects + the compacted format that `xsavec` writes; its rules are listed under "Compacted XRSTOR" below Per Intel SDM Vol. 1 Ch. 13.5.1, hardware `XSAVE` may report `XSTATE_BV[1:0] = 1` for initialized legacy x87/SSE components when selected by `RFBM` (observed directly on hybrid @@ -1717,9 +1718,55 @@ ctest --preset dev --no-tests=error -R '^cpu_aot_xsave_state$' -V ### Measured results and open scope +#### Compacted XRSTOR + +`xrstor` and `xrstor64` restore the compacted format when `XCOMP_BV[63]` is set. Only x87 (bit 0), SSE (bit 1) +and AVX (bit 2) exist in the model, so the legacy area keeps x87 and SSE and the AVX slot is the first extended +slot, offset 576. The rules below were measured with a small native program on one host, an `AuthenticAMD` +KVM guest that reports itself as "QEMU Virtual CPU version 2.5+" (family 15, model 107, `XCR0 = 7`, an +832-byte area, `CPUID.(0DH,1):EAX = 7`: XSAVEOPT, XSAVEC and XGETBV(1), no XSAVES). Every combination was run in a +child process, a fault being the child's SIGSEGV, after a restore of a different live state, so a component +that is left alone, initialized or restored can be told apart: + +| Header and request | Result on the host | +|---|---| +| `XCOMP_BV[62:0]` has any of bits 3 to 9 or 62 | `#GP` | +| `XSTATE_BV` has a bit `XCOMP_BV[62:0]` does not (bit 63 and bit 3 included) | `#GP` | +| any non-zero byte of `[528..575]` (all 48 bytes tried) | `#GP` | +| 64-byte misaligned address (+8, +16, +32) | `#GP` | +| `XCOMP_BV[63]` clear and any other `XCOMP_BV` bit set | `#GP` (the standard-format rule) | +| `XCOMP_BV = bit 63` alone, `RFBM = 7` | valid, every component initialized | +| `RFBM` has a component and `XSTATE_BV` and `XCOMP_BV` both list it | restored from its slot | +| `RFBM` has a component and `XSTATE_BV` does not list it, or `XCOMP_BV` leaves it out | initialized | +| `RFBM` does not have a component | untouched | +| MXCSR, `RFBM[1]` and `XSTATE_BV[1]` set | loaded, and `#GP` for reserved bits | +| MXCSR, `RFBM[1]` set and `XSTATE_BV[1]` clear | reset to `0x1F80`, the image word is not read | +| MXCSR, `RFBM[1]` clear (also `RFBM = 4`) | untouched | + +The 216 combinations of `XCOMP_BV[2:0]`, `XSTATE_BV` (a subset of it) and `RFBM` follow these rules. The +standard format on the same host loads MXCSR whenever `RFBM[2:1]` is not 0, as the model already did, and checks only +`[528..535]` of the header. `xsavec` leaves `[528..575]` alone, so a program that restores a buffer `xsavec` filled +must zero those bytes first; the round-trip fixtures do. A request bit outside `XCR0` is masked by the host +instead of faulting; the translator keeps its bound (`#GP` for `RFBM` bits above 2), checked on lifted code only. +`XGETBV(1)` after each restore agreed with the `XINUSE` bookkeeping of the model, which does not model `XMODIFIED`. +Only this one vendor and CPU family was measured: the MXCSR rule matches what `xsavec` writes (MXCSR is stored with +the SSE component only), but an Intel result could differ and no Intel host was available. + +`cpu_aot_xsave_state` covers it with six more exports in [the fixture](../tests/cpu/xsave_state.asm): five +`xsavec` to `xrstor` round trips of the same buffer (RFBM 7 to 7, x87|AVX to 7, x87|SSE to 7, 7 to AVX and 7 to +SSE) with a second live state restored in between, and one that restores a hand-built compacted image with its request +mask read from the image. The check runs them on ten states: 50 round trips (one also against a direct restore of +the saved image), the 216-combination matrix plus four MXCSR cases, 25 `#GP` controls (each invalid header field, +misalignment, request masks outside x87|SSE|AVX) with the output left untouched, and `ALTER_OP` variants of two +round trips that must diverge. Eleven mutation controls drop one rule from the reference model, the subset check, the +reserved bytes, the `XCOMP_BV` bit check and the compacted MXCSR rule, and the comparison must catch each. Native runs +are gated on `CPUID.(0DH,1):EAX[1]` like the `xsavec` fixtures, because a compacted restore needs it. The native +comparison accepts a host that reports `XSTATE_BV[1]` clear for SSE held only by a non-default MXCSR over zero XMM +state, the quirk recorded for `xsaveopt`. + The native harness probes whether the host preserves the 16-bit FCS and FDS values in the non-REX.W legacy area after XRSTOR/XSAVE. A measured zero is expected only at the corresponding native selector bytes. Lifted results still follow the separately specified CPUID-based profile. -The [MASM fixture](../tests/cpu/xsave_state.asm) exports 22 functions covering opt-in +The [MASM fixture](../tests/cpu/xsave_state.asm) exports 28 functions covering opt-in canonical-entry `xsave`/`xsave64` (`cpu_xsave_state_canonical_lifted`), `xrstor`/`xrstor64` roundtrips, displaced `[rcx+64]`/`[r8+64]`, `RFBM = 2` SSE-only masking (and `ALTER_OP` `RFBM = 2 -> 7` under `cpu_xsave_state_canonical_altered_lifted`), `vzeroupper` clearing diff --git a/tests/cpu/xsave_state.asm b/tests/cpu/xsave_state.asm index 09fd2a009..e729ca0b0 100644 --- a/tests/cpu/xsave_state.asm +++ b/tests/cpu/xsave_state.asm @@ -1,7 +1,7 @@ ; coverage: source cpu_aot_xsave_state ; Source-built MASM fixture exercising 8 XSAVE state forms from docs/coverage/x64_zen2.tsv -; group XSAVE: xsave, xsave64, xsavec, xsavec64, xsaveopt, xsaveopt64, xrstor, and xrstor64, along with transport/ABI glue -; (vmovdqu, vzeroupper, paddd, movq, emms). +; group XSAVE: xsave, xsave64, xsavec, xsavec64, xsaveopt, xsaveopt64, xrstor, and xrstor64 (standard and compacted +; format), along with transport/ABI glue (vmovdqu, vzeroupper, paddd, movq, emms). ; Every export uses the Windows x64 leaf ABI: ; RCX = const void* input_a (64-byte aligned; 960+ bytes) ; RDX = const void* input_b (64-byte aligned; 960+ bytes) @@ -247,6 +247,149 @@ op_xsaveopt64_dynmask PROC FRAME ret op_xsaveopt64_dynmask ENDP +; --- XRSTOR / XRSTOR64 of the compacted format --- +; Every export first restores input_a (a standard image with every component live), so each component starts +; defined, then restores a compacted image and stores the whole state with xsave64 over the output. + +; XSAVEC writes the compacted image into the output, XRSTOR of input_b (a standard image with other live state) +; replaces the registers, and XRSTOR of the SAME compacted buffer must bring input_a's state back. The header +; bytes [528..575] are zeroed first because xsavec leaves them alone and a compacted restore rejects them. +op_xsavec_xrstor_all PROC FRAME + .endprolog + mov r10, rdx + xor r9d, r9d + mov eax, 7 + xor edx, edx + xrstor64 [rcx] + mov QWORD PTR [r8+528], r9 + mov QWORD PTR [r8+536], r9 + mov QWORD PTR [r8+544], r9 + mov QWORD PTR [r8+552], r9 + mov QWORD PTR [r8+560], r9 + mov QWORD PTR [r8+568], r9 + xsavec64 [r8] + xrstor64 [r10] +IFDEF ALTER_OP + xrstor64 [r10] +ELSE + xrstor64 [r8] +ENDIF + xsave64 [r8] + ret +op_xsavec_xrstor_all ENDP + +; XSAVEC of x87|AVX leaves SSE out of XCOMP_BV: restoring RFBM = 7 initializes SSE and MXCSR (32-bit xrstor). +op_xsavec_xrstor_x87_avx PROC FRAME + .endprolog + mov r10, rdx + xor r9d, r9d + mov eax, 7 + xor edx, edx + xrstor64 [rcx] + mov QWORD PTR [r8+528], r9 + mov QWORD PTR [r8+536], r9 + mov QWORD PTR [r8+544], r9 + mov QWORD PTR [r8+552], r9 + mov QWORD PTR [r8+560], r9 + mov QWORD PTR [r8+568], r9 + mov eax, 5 + xsavec64 [r8] + mov eax, 7 + xrstor64 [r10] + xrstor [r8] + xsave64 [r8] + ret +op_xsavec_xrstor_x87_avx ENDP + +; XSAVEC of x87|SSE leaves AVX out of XCOMP_BV: restoring RFBM = 7 initializes AVX. +op_xsavec_xrstor_x87_sse PROC FRAME + .endprolog + mov r10, rdx + xor r9d, r9d + mov eax, 7 + xor edx, edx + xrstor64 [rcx] + mov QWORD PTR [r8+528], r9 + mov QWORD PTR [r8+536], r9 + mov QWORD PTR [r8+544], r9 + mov QWORD PTR [r8+552], r9 + mov QWORD PTR [r8+560], r9 + mov QWORD PTR [r8+568], r9 + mov eax, 3 + xsavec64 [r8] + mov eax, 7 + xrstor64 [r10] + xrstor64 [r8] + xsave64 [r8] + ret +op_xsavec_xrstor_x87_sse ENDP + +; RFBM = AVX alone restores only YMM[255:128]: x87, XMM and MXCSR keep input_b's values. +op_xsavec_xrstor_avx_only PROC FRAME + .endprolog + mov r10, rdx + xor r9d, r9d + mov eax, 7 + xor edx, edx + xrstor64 [rcx] + mov QWORD PTR [r8+528], r9 + mov QWORD PTR [r8+536], r9 + mov QWORD PTR [r8+544], r9 + mov QWORD PTR [r8+552], r9 + mov QWORD PTR [r8+560], r9 + mov QWORD PTR [r8+568], r9 + xsavec64 [r8] + xrstor64 [r10] + mov eax, 4 +IFDEF ALTER_OP + mov eax, 6 +ENDIF + xrstor64 [r8] + mov eax, 7 + xsave64 [r8] + ret +op_xsavec_xrstor_avx_only ENDP + +; RFBM = SSE alone restores XMM and MXCSR from the compacted image; x87 and AVX keep input_b's values. +op_xsavec_xrstor_sse_only PROC FRAME + .endprolog + mov r10, rdx + xor r9d, r9d + mov eax, 7 + xor edx, edx + xrstor64 [rcx] + mov QWORD PTR [r8+528], r9 + mov QWORD PTR [r8+536], r9 + mov QWORD PTR [r8+544], r9 + mov QWORD PTR [r8+552], r9 + mov QWORD PTR [r8+560], r9 + mov QWORD PTR [r8+568], r9 + xsavec64 [r8] + xrstor64 [r10] + mov eax, 2 + xrstor64 [r8] + mov eax, 7 + xsave64 [r8] + ret +op_xsavec_xrstor_sse_only ENDP + +; input_b is a hand-built compacted image and its RFBM comes from input_b itself (RAX = [rdx+832], +; RDX = [rdx+840]); the state it restores over input_a's is then stored with xsave64. +op_xrstor64_compacted_dynmask PROC FRAME + .endprolog + mov r10, rdx + mov eax, 7 + xor edx, edx + xrstor64 [rcx] + mov rax, QWORD PTR [r10+832] + mov rdx, QWORD PTR [r10+840] + xrstor64 [r10] + mov eax, 7 + xor edx, edx + xsave64 [r8] + ret +op_xrstor64_compacted_dynmask ENDP + ; --- Chained AVX + SSE + MMX + XSAVE64 pipeline and dead-read fault ordering --- op_pipeline PROC FRAME diff --git a/tests/cpu/xsave_state.def b/tests/cpu/xsave_state.def index 217a1e075..099ba93cd 100644 --- a/tests/cpu/xsave_state.def +++ b/tests/cpu/xsave_state.def @@ -22,3 +22,9 @@ EXPORTS op_xrstor64_xsaveopt64_x87_avx op_xrstor64_xsaveopt64_avx op_xsaveopt64_dynmask + op_xsavec_xrstor_all + op_xsavec_xrstor_x87_avx + op_xsavec_xrstor_x87_sse + op_xsavec_xrstor_avx_only + op_xsavec_xrstor_sse_only + op_xrstor64_compacted_dynmask diff --git a/tests/cpu/xsave_state_check.py b/tests/cpu/xsave_state_check.py index a22fa14a0..8bd7e4262 100644 --- a/tests/cpu/xsave_state_check.py +++ b/tests/cpu/xsave_state_check.py @@ -42,6 +42,20 @@ ) XSAVEOPT_DYNMASK_EXPORT = "op_xsaveopt64_dynmask" +# XSAVEC then XRSTOR of the same buffer: (xsavec RFBM, xrstor RFBM). The save mask leaves a component out of XCOMP_BV +# when it is not 7, and the restore mask selects which components come back from the compacted image. +COMPACTED_ROUNDTRIPS = { + "op_xsavec_xrstor_all": (7, 7), + "op_xsavec_xrstor_x87_avx": (5, 7), + "op_xsavec_xrstor_x87_sse": (3, 7), + "op_xsavec_xrstor_avx_only": (7, 4), + "op_xsavec_xrstor_sse_only": (7, 2), +} +COMPACTED_DYNMASK_EXPORT = "op_xrstor64_compacted_dynmask" +COMPACTED_EXPORTS = tuple(COMPACTED_ROUNDTRIPS) + (COMPACTED_DYNMASK_EXPORT,) +ALTERED_COMPACTED_EXPORTS = ("op_xsavec_xrstor_all", "op_xsavec_xrstor_avx_only") +GP_MESSAGE = "access violation reading 0xffffffffffffffff" + DEFINED_EXPORTS = ( "op_xrstor_xsave", "op_xrstor64_xsave64", @@ -319,12 +333,47 @@ def __init__(self, mxcsr_mask: int, deprecates_fpu_cs_ds: bool): self.ymm_hi = [bytearray(16) for _ in range(16)] self.xinuse = 0 - def xrstor(self, buf: bytes, rfbm: int, is64: bool) -> None: + def xrstor( + self, + buf: bytes, + rfbm: int, + is64: bool, + *, + check_subset: bool = True, + check_reserved: bool = True, + check_xcomp: bool = True, + compacted_mxcsr: bool = True, + ) -> None: + """Standard and compacted XRSTOR; the keyword flags are the mutation controls, each off drops one rule. + + Compacted (XCOMP_BV[63] set, measured on hardware): the header must list only x87|SSE|AVX, XSTATE_BV must be + a subset of it, and bytes [528..575] must be zero. A requested component restores when XSTATE_BV lists it + and initializes otherwise (a component XCOMP_BV leaves out is initialized). MXCSR belongs to the SSE + component: loaded when RFBM[1] and XSTATE_BV[1] are set, reset to 0x1F80 when only RFBM[1] is set, and left + alone when RFBM[1] is clear. compacted_mxcsr=False applies the standard rule (loaded for RFBM[2:1] != 0). + """ rfbm &= 7 xstate_bv, xcomp_bv, hdr_reserved = struct.unpack_from("> 63) + if compacted: + listed = xcomp_bv & ~(1 << 63) + if check_reserved and any(buf[528:576]): + raise ValueError("compacted header bytes [528..575] are not zero") + if check_xcomp and listed & ~7: + raise ValueError(f"XCOMP_BV lists components outside x87|SSE|AVX: {listed:#x}") + if check_subset and xstate_bv & ~listed: + raise ValueError(f"XSTATE_BV {xstate_bv:#x} is not a subset of XCOMP_BV {listed:#x}") + xstate_bv &= listed + loads_mxcsr = bool(xstate_bv & 2) and bool(rfbm & 2) + resets_mxcsr = bool(rfbm & 2) and not loads_mxcsr + if not compacted_mxcsr: + loads_mxcsr, resets_mxcsr = bool(rfbm & 6), False + else: + if xcomp_bv != 0 or hdr_reserved != 0 or (xstate_bv & ~7): + raise ValueError("invalid XSAVE header") + loads_mxcsr, resets_mxcsr = bool(rfbm & 6), False + new_mxcsr = DEFAULT_MXCSR if resets_mxcsr else self.mxcsr + if loads_mxcsr: new_mxcsr = struct.unpack_from(" None: self.fds = 0 self.st = [bytearray(16) for _ in range(8)] self.xinuse &= ~1 - if rfbm & 6: - self.mxcsr = new_mxcsr + self.mxcsr = new_mxcsr if rfbm & 2: if xstate_bv & 2: for i in range(16): @@ -689,7 +737,7 @@ def _xsave_header_flex(name: str) -> tuple[int, int] | None: return 64 + 512, 7 if name == "op_xrstor64_mask_sse": return 512, 2 - if name in EXPORTS: + if name in EXPORTS or name in COMPACTED_EXPORTS: return 512, 7 return None @@ -785,11 +833,16 @@ def assert_equal_output(label: str, name: str, idx, got: bytes, want: bytes) -> def native_exports_for_host(native: dict, has_xsavec: bool, has_xsaveopt: bool = True) -> dict: - """Drop native xsavec/xsaveopt fixtures on hosts without them: executing them would raise #UD.""" + """Drop native xsavec/xsaveopt fixtures on hosts without them: executing them would raise #UD. + + The compacted XRSTOR fixtures go with XSAVEC: the compacted format is enumerated by the same CPUID bit, and + without it a restore with XCOMP_BV[63] set always raises #GP. + """ return { name: fn for name, fn in native.items() - if (has_xsavec or name not in XSAVEC_EXPORTS) and (has_xsaveopt or name not in XSAVEOPT_EXPORTS) + if (has_xsavec or (name not in XSAVEC_EXPORTS and name not in COMPACTED_EXPORTS)) + and (has_xsaveopt or name not in XSAVEOPT_EXPORTS) } @@ -1314,6 +1367,297 @@ def must_fail(label, got, want, expect_byte=None): return controls + 1 +# --- Compacted-format XRSTOR --- + +def reference_compacted( + name: str, a: bytes, b: bytes, mxcsr_mask: int, deprecates_cs_ds: bool, altered: bool = False, **mutations +) -> bytes: + """Expected output of a compacted-XRSTOR export; ValueError where the instruction raises #GP.""" + out = bytearray(FILL) + model = XStateModel(mxcsr_mask, deprecates_cs_ds) + model.xrstor(a, rfbm=7, is64=True) + if name == COMPACTED_DYNMASK_EXPORT: + mask_lo, mask_hi = struct.unpack_from(" bytes: + """Hand-built compacted image for the dynmask export: header, payloads at their compacted slots, RFBM at [832].""" + buf = bytearray( + make_xsave_image(mxcsr_mask, xstate_bv=xstate_bv, fcw=0x0F7F, fop=0, mxcsr=mxcsr, seed=seed) + ) + struct.pack_into("> (8 * i)) & 0xFF) for i in range(4)) + for label, xstate_bv, listed, rfbm in ( + ("bad-mxcsr-sse-restored", 2, 7, 7), + ("bad-mxcsr-sse-only", 2, 7, 2), + ("bad-mxcsr-sse-init", 0, 7, 7), + ("bad-mxcsr-avx-only-request", 4, 7, 4), + ("bad-mxcsr-sse-not-listed", 1, 5, 7), + ("bad-mxcsr-x87-only-request", 3, 7, 1), + ): + cases.append(( + label, base, compacted_image(mxcsr_mask, xstate_bv, COMPACTED_BIT | listed, rfbm, pokes=mxcsr_pokes) + )) + return cases + + +def run_compacted(label: str, harness, fn, a: bytes, b: bytes, *, b_offset: int = 0): + """Call one export (harness is None for lifted code); returns (faulted with #GP, output bytes).""" + buf_a, ptr_a, a_pre, a_off, a_post = alloc_aligned_buffer(a) + buf_b, ptr_b, b_pre, b_off, b_post = alloc_aligned_buffer(b, offset=b_offset) + buf_out, ptr_out, o_pre, o_off, o_post = alloc_aligned_buffer(FILL) + faulted = False + try: + if harness is not None: + harness.call_native(fn, ptr_a, ptr_b, ptr_out) + else: + fn(ptr_a, ptr_b, ptr_out) + except OSError as exc: + assert GP_MESSAGE in str(exc).lower(), (label, exc) + faulted = True + check_guards_and_read(buf_a, a_pre, a_off, a_post, f"{label} input_a") + check_guards_and_read(buf_b, b_pre, b_off, b_post, f"{label} input_b") + return faulted, check_guards_and_read(buf_out, o_pre, o_off, o_post, f"{label} output") + + +def expected_compacted(*args, **kwargs): + """The reference output, or None where the instruction raises #GP.""" + try: + return reference_compacted(*args, **kwargs) + except ValueError: + return None + + +def check_compacted_run(side: str, name: str, label, harness, fn, a: bytes, b: bytes, want, *, b_offset: int = 0) -> None: + faulted, got = run_compacted(f"{side} {name} {label}", harness, fn, a, b, b_offset=b_offset) + if want is None: + assert faulted, f"{side} {name} {label} accepted a header the instruction rejects" + assert got == FILL, f"{side} {name} {label}: output written before the #GP" + else: + assert not faulted, f"{side} {name} {label} raised #GP for a valid compacted restore" + want_bv = struct.unpack_from(" dict: + """XSAVEC -> XRSTOR round trips, hand-built compacted headers, their #GP rules and the mutation controls.""" + counts = {"roundtrip": 0, "header": 0, "gp": 0, "altered": {}, "controls": 0} + + def model(name, a, b, **mutations): + return expected_compacted(name, a, b, mxcsr_mask, deprecates_cs_ds, **mutations) + + for name in COMPACTED_ROUNDTRIPS: + for idx, (a, b) in enumerate(compact_state_pairs(mxcsr_mask)): + want = model(name, a, b) + assert want is not None + check_compacted_run("lifted", name, idx, None, lifted[name], a, b, want) + if name in native: + check_compacted_run("native", name, idx, harness, native[name], a, b, want) + counts["roundtrip"] += 1 + if name == "op_xsavec_xrstor_all": + # Independent oracle: a full save and restore of the same state brings back exactly what a direct + # restore of the image gives, in the legacy area and the AVX area. + direct = reference("op_xrstor64_xsave64", a, a, mxcsr_mask, deprecates_cs_ds) + assert want[:512] == direct[:512] and want[576:832] == direct[576:832], f"round trip case {idx}" + + cases = compacted_cases(mxcsr_mask) + for label, a, b in cases: + want = model(COMPACTED_DYNMASK_EXPORT, a, b) + check_compacted_run("lifted", COMPACTED_DYNMASK_EXPORT, label, None, lifted[COMPACTED_DYNMASK_EXPORT], a, b, want) + if COMPACTED_DYNMASK_EXPORT in native: + check_compacted_run( + "native", COMPACTED_DYNMASK_EXPORT, label, harness, native[COMPACTED_DYNMASK_EXPORT], a, b, want + ) + counts["header"] += want is not None + counts["gp"] += want is None + + # A misaligned compacted image faults like a misaligned standard one, before anything is stored. + mis_a, mis_b = compact_state_pairs(mxcsr_mask)[0][0], compacted_image(mxcsr_mask, 7, COMPACTED_BIT | 7, 7) + for off in (8, 16): + check_compacted_run("lifted", COMPACTED_DYNMASK_EXPORT, f"misaligned+{off}", None, + lifted[COMPACTED_DYNMASK_EXPORT], mis_a, mis_b, None, b_offset=off) + if COMPACTED_DYNMASK_EXPORT in native: + check_compacted_run("native", COMPACTED_DYNMASK_EXPORT, f"misaligned+{off}", harness, + native[COMPACTED_DYNMASK_EXPORT], mis_a, mis_b, None, b_offset=off) + counts["gp"] += 1 + + # Request masks outside x87|SSE|AVX are this translator's own bound (hardware masks them with XCR0): lifted only. + for mask_lo, mask_hi in ((8, 0), (0xF, 0), (7, 1)): + bad_mask_image = bytearray(compacted_image(mxcsr_mask, 0, COMPACTED_BIT | 7, 0)) + struct.pack_into(" int: + """Mutation controls: dropping one validity rule or the compacted MXCSR rule from the model must be caught.""" + by_label = {label: (a, b) for label, a, b in cases} + dyn = COMPACTED_DYNMASK_EXPORT + controls = 0 + + # Each validity rule has a case only that rule rejects: the model without it accepts the header, the lifted code + # (and the host) fault, so a lowering that dropped the rule would show up as an accepted header. + for label, mutation in ( + ("xstate-avx-not-in-xcomp", {"check_subset": False}), + ("xstate-x87-xcomp-empty", {"check_subset": False}), + ("reserved-536", {"check_reserved": False}), + ("reserved-575", {"check_reserved": False}), + ("xcomp-bit3", {"check_xcomp": False}), + ("xcomp-bit62", {"check_xcomp": False}), + ): + a, b = by_label[label] + assert expected_compacted(dyn, a, b, mxcsr_mask, deprecates_cs_ds) is None, label + accepted = expected_compacted(dyn, a, b, mxcsr_mask, deprecates_cs_ds, **mutation) + assert accepted is not None, f"mutation {mutation} still rejects {label}" + faulted, _ = run_compacted(f"control {label}", None, lifted[dyn], a, b) + assert faulted, f"lifted {label}" + try: + check_compacted_run("lifted", dyn, label, None, lifted[dyn], a, b, accepted) + except AssertionError: + controls += 1 + else: + raise AssertionError(f"comparison accepted the mutation {mutation} on {label}") + + # The compacted MXCSR rule against the standard one: the first differing byte is inside the MXCSR word [24..27]. + mxcsr_cases = [] + for label in ("xcomp7-rfbm7-xstate0", "xcomp7-rfbm4-xstate4", "xcomp5-rfbm7-xstate1"): + a, b = by_label[label] + mxcsr_cases.append((dyn, a, b, label)) + for name in ("op_xsavec_xrstor_avx_only", "op_xsavec_xrstor_x87_avx"): + a, b = compact_state_pairs(mxcsr_mask)[0] + mxcsr_cases.append((name, a, b, "roundtrip")) + for name, a, b, label in mxcsr_cases: + right = expected_compacted(name, a, b, mxcsr_mask, deprecates_cs_ds) + standard_rule = expected_compacted(name, a, b, mxcsr_mask, deprecates_cs_ds, compacted_mxcsr=False) + if right == standard_rule: + continue # the rules agree here: the loaded image MXCSR equals what the compacted rule gives + if standard_rule is None: + controls += 1 # the standard rule would load a reserved MXCSR the compacted save never wrote and fault + continue + _, got = run_compacted(f"control {name} {label}", None, lifted[name], a, b) + assert_equal_output("lifted", name, label, got, right) + try: + assert_equal_output("lifted", name, label, got, standard_rule) + except AssertionError as err: + assert any(f"first mismatch at byte {pos}:" in str(err) for pos in range(24, 28)), err + controls += 1 + else: + raise AssertionError(f"comparison accepted the standard MXCSR rule on {name} {label}") + assert controls >= 9, controls + return controls + + + def check_differential( native_path: Path, lifted_path: Path, @@ -1322,7 +1666,9 @@ def check_differential( canonical_altered_path: Path, native_altered_path: Path, ) -> None: - lifted_lib, lifted = bind_exports(lifted_path, "lifted_", DEFINED_EXPORTS + (DYNMASK_EXPORT, XSAVEOPT_DYNMASK_EXPORT)) + lifted_lib, lifted = bind_exports( + lifted_path, "lifted_", DEFINED_EXPORTS + (DYNMASK_EXPORT, XSAVEOPT_DYNMASK_EXPORT) + COMPACTED_EXPORTS + ) lifted_lib.host_has_xsave.argtypes = [] lifted_lib.host_has_xsave.restype = ctypes.c_uint32 if not lifted_lib.host_has_xsave(): @@ -1356,10 +1702,10 @@ def check_differential( fp_cpuid = int(lifted_lib.host_fp_err_cpuid_info()) mxcsr_mask = int(lifted_lib.host_mxcsr_mask()) - _, native = bind_exports(native_path) + _, native = bind_exports(native_path, "", EXPORTS + COMPACTED_EXPORTS) native = native_exports_for_host(native, has_xsavec, has_xsaveopt) _, native_altered = bind_exports(native_altered_path, "", ALTERED_CANONICAL_EXPORTS) - altered_lib, altered = bind_exports(altered_path, "lifted_", ALTERED_DEFINED_EXPORTS) + altered_lib, altered = bind_exports(altered_path, "lifted_", ALTERED_DEFINED_EXPORTS + ALTERED_COMPACTED_EXPORTS) canonical_lib, canonical = bind_exports(canonical_path, "lifted_", CANONICAL_EXPORTS) canonical_altered_lib, canonical_altered = bind_exports( canonical_altered_path, "lifted_", ALTERED_CANONICAL_EXPORTS @@ -1455,6 +1801,7 @@ def check_differential( liveness_checks = check_xsavec_mxcsr_liveness(harness, native, lifted, mxcsr_mask, deprecates_cs_ds) layout_checks = check_xsaveopt_layout(harness, native, lifted, mxcsr_mask) opt_controls = check_xsaveopt_controls(mxcsr_mask, deprecates_cs_ds) + compacted = check_compacted_xrstor(harness, native, lifted, altered, mxcsr_mask, deprecates_cs_ds) # Native comparison keeps active x87/SSE payloads: a flipped FCW, ST0 or XMM0 byte must fail, while an # initialized component carrying extra host bytes must still pass. @@ -1481,7 +1828,7 @@ def check_differential( # A host without XSAVEC must not be handed native xsavec fixtures. gated = native_exports_for_host(native, False, False) - unsupported = set(XSAVEC_EXPORTS) | set(XSAVEOPT_EXPORTS) + unsupported = set(XSAVEC_EXPORTS) | set(XSAVEOPT_EXPORTS) | set(COMPACTED_EXPORTS) assert not unsupported & set(gated) and set(native) - unsupported == set(gated) check_fault_controls(harness, gated, lifted, canonical, mxcsr_mask) @@ -1495,7 +1842,10 @@ def check_differential( f"{hdr_mxcsr_checks} header/MXCSR #GP checks, {mask_checks} unsupported-mask #GP checks, entry-state contract, non-default entry controls, " f"dead-read, host-state, and output mutation controls passed; " f"{liveness_checks} xsavec MXCSR-liveness checks passed; " - f"{layout_checks} xsaveopt layout readbacks and {opt_controls} xsaveopt mutation controls passed" + f"{layout_checks} xsaveopt layout readbacks and {opt_controls} xsaveopt mutation controls passed; " + f"compacted xrstor: {compacted['roundtrip']} xsavec round trips, {compacted['header']} valid and " + f"{compacted['gp']} #GP header cases, ALTER_OP diverged on {compacted['altered']}, " + f"{compacted['controls']} mutation controls passed" ) finally: harness.close() @@ -1555,6 +1905,14 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins))) + alt_accept.append(("xsavec_then_xrstor_same_buffer", ( + mov_eax_7, + xor_edx, + Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), + Instruction.create_mem(Code.XSAVEC64_MEM, MemoryOperand(R.R8)), + Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.R8)), + Instruction.create_mem(Code.XSAVE64_MEM, MemoryOperand(R.R8)), + ret_ins))) # MXCSR is defined by a restore selecting SSE or AVX; an x87-only save stores no MXCSR. alt_accept.append(("xrstor_avx_vzeroupper_xsaveopt64_avx", ( mov_eax_4, @@ -1573,6 +1931,7 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) "xrstor_r9_saved_rdx": "op_xrstor(state, r9, rax, rdx, true);", "xrstor3_vzeroupper_xsave7": "op_vzeroupper(state);", "xrstor_xsavec64": "op_xsavec(state, r8, rax, rdx, true);", + "xsavec_then_xrstor_same_buffer": "op_xrstor(state, r8, rax, rdx, true);", "xrstor_xsaveopt64": "op_xsaveopt(state, r8, rax, rdx, true);", "xrstor_avx_vzeroupper_xsaveopt64_avx": "op_xsaveopt(state, r8, rax, rdx, true);", "xrstor_x87_xsaveopt64_x87": "op_xsaveopt(state, r8, rax, rdx, true);", diff --git a/tools/cpu_xsave_aot.py b/tools/cpu_xsave_aot.py index 51d93773f..1936a8721 100644 --- a/tools/cpu_xsave_aot.py +++ b/tools/cpu_xsave_aot.py @@ -14,7 +14,9 @@ and partially initialized restore/save paths that observe uninitialized components from entry are rejected. MXCSR is tracked apart from the components: only an xrstor whose RFBM selects SSE or AVX defines it, so - vzeroupper alone does not, and a save that stores MXCSR (xsaveopt with SSE + vzeroupper alone does not (the format is data, not known when lifting: a compacted + restore selecting AVX without SSE leaves MXCSR alone, and the lifted state then + still holds its reset value 0x1F80), and a save that stores MXCSR (xsaveopt with SSE or AVX selected, xsave/xsavec with SSE selected) is rejected without it. - canonical (opt-in): permits xsave/xsave64 before full component definition assuming the native caller establishes canonical architectural XSAVE state @@ -47,17 +49,33 @@ modified optimization (XMODIFIED after a prior XRSTOR to the same address) is not modeled: the lifted code writes every component that is in use. - xrstor / xrstor64: require 64-byte-aligned [base + disp] and bounded mask - (edx == 0 && (eax & ~7) == 0); validate XCOMP_BV == 0, + (edx == 0 && (eax & ~7) == 0). The header selects the format. + Standard (XCOMP_BV[63] clear): validate XCOMP_BV == 0, header [528..535] == 0, (XSTATE_BV & ~7) == 0, and (when rfbm & 6 != 0) MXCSR against host MXCSR_MASK (#GP before mutating state), then restore or init each requested component and update XINUSE[2:0]. + Compacted (XCOMP_BV[63] set, the layout xsavec writes): + validate that XCOMP_BV[62:0] lists nothing outside + x87|SSE|AVX, that XSTATE_BV is a subset of XCOMP_BV[62:0] + and that every header byte [528..575] is zero (#GP before + mutating state). A requested component restores from its + compacted slot (x87 and SSE in the legacy area, AVX at 576, the + first extended slot) when XSTATE_BV and XCOMP_BV both list it, + and is initialized otherwise, which includes a component + XCOMP_BV does not list. MXCSR belongs to the SSE component: + loaded (and checked against MXCSR_MASK) when RFBM[1] and + XSTATE_BV[1] are set, reset to 0x1F80 when RFBM[1] is set and + XSTATE_BV[1] is clear, untouched when RFBM[1] is clear, so an + AVX-only restore keeps the current MXCSR. The xsavec writer + leaves bytes [528..575] alone, so a caller that restores a + buffer xsavec filled must have zeroed them first. Transport/ABI glue: vmovdqa/vmovdqu (XMM0..5, YMM0..5), vzeroupper, movdqa/movdqu (XMM0..5), paddd (XMM0..5), movq (MM0..7 <-> m64 / volatile scratch r64), emms, 32/64-bit volatile GPR mov/xor, and terminal ret. -XSAVES/XRSTORS, compacted XRSTOR, FXSAVE/FXRSTOR, EVEX encodings, nonvolatile +XSAVES/XRSTORS, FXSAVE/FXRSTOR, EVEX encodings, nonvolatile registers (XMM6..15, YMM6..15, ZMM0..15, RBX/RBP/RSI/RDI/R12..R15/RSP), non-argument memory bases, stores outside r8, RIP-relative/indexed addressing, prefixes, branches, unclosed MMX state before ret, and trailing bytes reject. @@ -316,6 +334,12 @@ return value; } +static inline void store64(word address, std::uint64_t value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + *reinterpret_cast(address) = value; + std::atomic_signal_fence(std::memory_order_seq_cst); +} + static inline Vec128 load128(word address, bool aligned) { if (aligned && (address & 15ull) != 0ull) raise_gp(); std::atomic_signal_fence(std::memory_order_seq_cst); @@ -468,13 +492,43 @@ std::memcpy(&xstate_bv, raw + 512, 8); std::memcpy(&xcomp_bv, raw + 520, 8); std::memcpy(&hdr_reserved, raw + 528, 8); - if (xcomp_bv != 0ull || hdr_reserved != 0ull) raise_gp(); - if ((xstate_bv & ~7ull) != 0ull) raise_gp(); + // XCOMP_BV[63] selects the compacted format. Only x87 (bit 0), SSE (bit 1) and AVX (bit 2) exist here. + const bool compacted = (xcomp_bv >> 63) != 0ull; + const std::uint64_t xcomp_components = xcomp_bv & ~(1ull << 63); + if (compacted) { + // Compacted header: every header byte after XCOMP_BV is reserved, XSTATE_BV must be a subset of the + // components XCOMP_BV lists, and XCOMP_BV may list nothing outside x87|SSE|AVX. + for (unsigned i = 528u; i < 576u; i += 8u) { + std::uint64_t word = 0ull; + std::memcpy(&word, raw + i, 8); + if (word != 0ull) raise_gp(); + } + if ((xcomp_components & ~7ull) != 0ull) raise_gp(); + if ((xstate_bv & ~xcomp_components) != 0ull) raise_gp(); + } else { + if (xcomp_bv != 0ull || hdr_reserved != 0ull) raise_gp(); + if ((xstate_bv & ~7ull) != 0ull) raise_gp(); + } + // MXCSR: the standard format loads it whenever RFBM selects SSE or AVX. The compacted format keeps it with + // the SSE component only: loaded when RFBM[1] and XSTATE_BV[1] are set, reset to 0x1F80 when RFBM[1] is set + // and XSTATE_BV[1] is clear, and left alone when RFBM[1] is clear (an AVX-only restore does not touch it). + // The #GP check applies to a loaded value only. std::uint32_t new_mxcsr = 0u; - if ((rfbm & 6ull) != 0ull) { - std::memcpy(&new_mxcsr, raw + 24, 4); - if ((new_mxcsr & ~state.mxcsr_mask) != 0u) raise_gp(); + bool restores_mxcsr = false; + if (!compacted) { + restores_mxcsr = (rfbm & 6ull) != 0ull; + if (restores_mxcsr) { + std::memcpy(&new_mxcsr, raw + 24, 4); + if ((new_mxcsr & ~state.mxcsr_mask) != 0u) raise_gp(); + } + } else if ((rfbm & 2ull) != 0ull) { + restores_mxcsr = true; + new_mxcsr = 0x1F80u; + if ((xstate_bv & 2ull) != 0ull) { + std::memcpy(&new_mxcsr, raw + 24, 4); + if ((new_mxcsr & ~state.mxcsr_mask) != 0u) raise_gp(); + } } if ((rfbm & 1ull) != 0ull) { @@ -522,7 +576,7 @@ } } - if ((rfbm & 6ull) != 0ull) { + if (restores_mxcsr) { state.mxcsr = new_mxcsr; } @@ -540,6 +594,7 @@ if ((rfbm & 4ull) != 0ull) { if ((xstate_bv & 4ull) != 0ull) { + // The compacted AVX slot is the first extended slot, 576, as x87 and SSE live in the legacy area. for (unsigned i = 0; i < 16u; ++i) { std::memcpy(state.ymm_hi[i], raw + 576u + i * 16u, 16); } From dd73bde1722d79f77268a8eac73ea5770391de21 Mon Sep 17 00:00:00 2001 From: RenzoWit35 <168984533+RenzoWit35@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:45:55 +0100 Subject: [PATCH 008/775] tooling: add mid-body RSP generators to the CPU fuzz test Add --area rsp to tools/fuzz_cpu.py and the CTest cpu_aot_fuzz_rsp, with its own seed (CPU_FUZZ_RSP_SEED=0xB0D1, CPU_FUZZ_RSP_FUNCTIONS=36). Each export moves RSP after its prologue: SUB and ADD RSP, PUSH and POP of saved registers that hold data, two branch arms that reach the same depth in different ways, a SUB RSP that aligns a direct call, and RBP anchored frames that end with LEAVE or POP RBP. Stores and reloads reach the same frame bytes through different [RSP+d] and [RBP+d] displacements, and the generator only reads bytes the translator treats as defined. Four refused controls: a reload of released bytes, a join at two depths, a read below RSP and SUB RSP, 4. The planted fault stale_rsp resolves every [RSP+d] operand against the RSP after the prologue's allocation; the test fails unless it differs from native. The emit output of the six existing areas is byte-identical. --- CMakeLists.txt | 41 +++++ docs/experiments.md | 2 + tools/fuzz_cpu.py | 419 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 460 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1381bac17..c645e5e61 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1858,6 +1858,47 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$" "${cpu_fuzz_scalar_fp_o2}" --area scalar_fp --mutant "$") set_tests_properties(cpu_aot_fuzz_scalar_fp PROPERTIES TIMEOUT 60) + + # Mid-body RSP changes (SUB and ADD RSP, PUSH and POP, arms, calls, RBP anchors), with a stale RSP planted. + set(CPU_FUZZ_RSP_SEED "0xB0D1" CACHE STRING "Seed for the CPU differential fuzz mid-body RSP test") + set(CPU_FUZZ_RSP_FUNCTIONS "36" CACHE STRING "Number of exported functions in the CPU differential fuzz mid-body RSP test") + set(cpu_fuzz_rsp_asm "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_rsp.asm") + set(cpu_fuzz_rsp_def "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_rsp.def") + add_custom_command(OUTPUT "${cpu_fuzz_rsp_asm}" "${cpu_fuzz_rsp_def}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" emit + "${CPU_FUZZ_RSP_SEED}" "${CPU_FUZZ_RSP_FUNCTIONS}" "${cpu_fuzz_rsp_asm}" + "${cpu_fuzz_rsp_def}" --area rsp + DEPENDS tools/fuzz_cpu.py VERBATIM) + add_library(cpu_fuzz_rsp SHARED "${cpu_fuzz_rsp_asm}" "${cpu_fuzz_rsp_def}") + set_target_properties(cpu_fuzz_rsp PROPERTIES LINKER_LANGUAGE CXX) + target_link_options(cpu_fuzz_rsp PRIVATE /NOENTRY /NODEFAULTLIB /INCREMENTAL:NO /OPT:NOICF) + set(cpu_fuzz_rsp_lifted "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_rsp_lifted.cpp") + set(cpu_fuzz_rsp_mutant "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_rsp_mutant.cpp") + foreach(variant lifted mutant) + set(mutant_flag "") + if(variant STREQUAL "mutant") + set(mutant_flag "--mutant") + endif() + add_custom_command(OUTPUT "${cpu_fuzz_rsp_${variant}}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" translate + "${CPU_FUZZ_RSP_SEED}" "${CPU_FUZZ_RSP_FUNCTIONS}" "$" + "${cpu_fuzz_rsp_${variant}}" --area rsp ${mutant_flag} + DEPENDS cpu_fuzz_rsp tools/fuzz_cpu.py tools/cpu_switch_aot.py tools/cpu_leaf_aot.py + tools/cpu_call_aot.py tools/cpu_ranges.py VERBATIM) + add_library(cpu_fuzz_rsp_${variant} SHARED "${cpu_fuzz_rsp_${variant}}") + target_compile_features(cpu_fuzz_rsp_${variant} PRIVATE cxx_std_20) + endforeach() + set(cpu_fuzz_rsp_o2 "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_rsp_lifted_o2.dll") + add_custom_command(OUTPUT "${cpu_fuzz_rsp_o2}" + COMMAND "${CMAKE_CXX_COMPILER}" /nologo /O2 /W4 /LD "${cpu_fuzz_rsp_lifted}" + "/Fo${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_rsp_lifted_o2.obj" "/Fe${cpu_fuzz_rsp_o2}" + DEPENDS "${cpu_fuzz_rsp_lifted}" VERBATIM) + add_custom_target(cpu_fuzz_rsp_lifted_o2 ALL DEPENDS "${cpu_fuzz_rsp_o2}") + add_test(NAME cpu_aot_fuzz_rsp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" check "${CPU_FUZZ_RSP_SEED}" "${CPU_FUZZ_RSP_FUNCTIONS}" + "$" "$" "${cpu_fuzz_rsp_o2}" + --area rsp --mutant "$") + set_tests_properties(cpu_aot_fuzz_rsp PROPERTIES TIMEOUT 60) cpu_asm_fixture(cpu_switch_addr32 switch_addr32) cpu_asm_fixture(cpu_switch_strings switch_strings) cpu_asm_fixture(cpu_string_probe string_probe) diff --git a/docs/experiments.md b/docs/experiments.md index d6f1c26a3..f3c931b8a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2494,6 +2494,8 @@ Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_smoke$' -V`. `CPU_FUZ `cpu_aot_fuzz_scalar_fp` (`--area scalar_fp`) covers the scalar SSE and SSE2 lifter [`cpu_sse_aot`](../tools/cpu_sse_aot.py) from its own seed, so the areas above are unchanged (their `emit` output is byte-identical to the previous revision). Every export is fn(x, y, out) and carries the descriptor that `cpu_sse_aot` takes, `=:`, which the generator writes as `Function.signature` (for example `d:fdq`). The first two slots are a float (`f`), a double (`d`) or a 64-bit integer (`q`), passed in XMM0 and XMM1 or in RCX and RDX by slot number, and the third is the output buffer in R8. The result is a float or double in XMM0 or an integer in RAX. The check passes a float or double slot as a `ctypes` double with the whole 64 bits set to the value (a float takes the low 32 bits and a fixed pattern above them, which the function must ignore) and reads a float result as the low 32 bits of the returned double. A float or double result is compared bit for bit, including every NaN payload and the sign of zero, together with the 256-byte output buffer: the translator models those bits (it quiets a signalling NaN, returns the destination NaN before the source one, and gives the default NaN for an invalid operation), the fixtures in `tests/cpu/scalar_float.asm` compare them, and nothing is masked. The 60 default exports cycle through six profiles (float arithmetic, double arithmetic, MIN and MAX, compares with jumps, conversions, and a mixture) and use ADDSS, SUBSS, MULSS, DIVSS, SQRTSS, MINSS, MAXSS and the SD forms; UCOMISS, UCOMISD, COMISS and COMISD followed by one conditional jump (`JE`, `JNE`, `JB`, `JAE`, `JBE`, `JA`, `JP`, `JNP`) or by a parity jump and then an ordered one, with an arm for each outcome and a join; CVTSS2SD, CVTSD2SS, CVTSI2SS and CVTSI2SD from a 32- or 64-bit register or memory, CVTTSS2SI and CVTTSD2SI to a 32- or 64-bit register; MOVAPS, MOVSS, MOVSD, MOVQ and MOVD between registers, from and to the output buffer, and to and from a general register; and the zeroing XORPS, XORPD and PXOR. Memory operands are always in the output buffer, which each function first fills with its arguments, and the function writes every live register back to it before it returns. The generator tracks which low dword or quadword of each XMM register and which general registers are defined, and reads only what the translator accepts; the upper dword of a float argument is never read. The check inputs for each export are the 17 x 17 combinations of 17 edge values of the kind of each slot (zeros of both signs, one, 1.5, the smallest and largest denormals, the smallest normal, the largest finite value, both infinities, quiet NaNs, a NaN with a payload, a signalling NaN, and the values at 2^31 and 2^63) and 24 pairs of further edges (just inside and outside the 32- and 64-bit integer conversion limits) and random bits. SETcc and CMOVcc after a float compare are not generated, because `cpu_sse_aot` refuses them (the flags of a float compare feed jumps only). Four negative controls in the same DLL are translated one at a time, and the test fails unless each is refused for its own reason: SETcc after UCOMISS (`unsupported flag producer`), `JLE` after UCOMISS (`unsupported condition after a float compare`), a read of an XMM register that was never written (`undefined register xmm2`) and an ADDSD on a float argument (`undefined register xmm0[63:32]`). MOVQ between a general register and an XMM register, CVTSS2SI and CVTSD2SI (which round by MXCSR), packed and VEX forms and any write to MXCSR are not generated. The planted translator fault, `--mutant` (`minmax_swap`), makes MINSS and MINSD keep the larger operand and MAXSS and MAXSD the smaller, in the translator's table; the test fails unless that build differs from native. Without MSVC, this was run on Linux with `llvm-ml-19` and `lld-link-19` (no rewrite of the MASM was needed), the real `cpu_sse_aot` translation, a MinGW build of it at `-O0` and `-O2` and a small loader under Wine that calls each export and prints its result bits and a hash of the buffer. At the default seed `0xF10A` (60 exports, 313 inputs each) the 18,780 calls per build had no mismatch at `-O0` or `-O2`; the 60 exports have 39 compares in 23 functions, 51 conditional jumps (17 of them in a parity pair), 75 truncations to an integer, 26 conversions from an integer, 54 float and double resizes, 149 arithmetic, 64 MIN and MAX and 38 SQRT operations. Seeds `0x1`, `0x2` and `0xBEEF` at 120 exports (37,560 calls per build) and `0xC0DE` at 100 exports (31,300) also had no refusal and no mismatch. The four controls were refused with the messages above. The planted fault differed in 3,742 of 18,780 calls (18 of 60 exports) at the default seed, and in 9,371, 8,388, 6,441 and 8,246 calls at the other four runs. The Python `check` command was run against native-code stand-ins built from the translation on Linux (the same 60 exports, 37,560 comparisons, controls refused, and the same 3,742 mutant mismatches), not against MSVC and ML64 output. The `ctest` run on Windows with MSVC and ML64 is not yet recorded here. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_scalar_fp$' -V`. `CPU_FUZZ_SCALAR_FP_SEED` and `CPU_FUZZ_SCALAR_FP_FUNCTIONS` select a longer run. The generator does not use stack slots (the leaf profile rejects stack operations), RIP-relative constants, MXCSR modes other than the host default, or nested compares. +`cpu_aot_fuzz_rsp` (`--area rsp`) covers mid-body RSP changes in the [translator](../tools/cpu_switch_aot.py) from its own seed, so the areas above are unchanged (their `emit` output is byte-identical to the previous revision at the default and the documented long-run seeds). Each export is fn(x, y, out). Its prologue pushes one to three of RBX, RSI, RDI and R12 to R15 and allocates 16 to 48 bytes, with the matching unwind directives, and every saved register is overwritten from RCX and RDX before it is read. After the prologue the body moves RSP again: `SUB RSP` and `ADD RSP` by 8 to 48 bytes, `PUSH` and `POP` of saved registers that hold data (a `POP` may load bytes that narrower stores wrote, or another register's pushed value), and stores, reloads and in-place updates of 1, 2, 4 or 8 bytes at any offset of the allocation, the caller's home space and what the body allocated itself. A reload prefers bytes that were stored at another RSP, so the same bytes are reached through different `[RSP+d]` displacements; every function has at least one such reload and four reloads in all, and every reloaded value goes to the output buffer and into RAX. The saved registers' final values are written to the buffer before the epilogue. The 36 default exports cycle through six shapes: adjustments only; mostly `PUSH` and `POP`; a `TEST` and a conditional jump whose two arms move RSP by the same amount in different ways (`SUB RSP` or `PUSH`, sometimes with an excursion that the arm releases again), so the join sees one depth and only the bytes both arms defined stay defined; a mid-body `SUB RSP` that aligns RSP for one or two direct calls to frameless callees that no export names, after which only RAX, the saved registers and the frame above the callee's home space are read; and two shapes with an RBP anchor (`PUSH RBP`, `MOV RBP, RSP`, `.setframe`) that address the same bytes through `[RBP+d]` and `[RSP+d]` at different depths and end with `LEAVE`, which releases whatever the body left allocated, or with `ADD RSP` and `POP RBP`. The generator follows which stack bytes are defined: the bytes that `ADD RSP` and `POP` release, and the callee's home space after a call, are never read again before they are written, because the translator treats them as undefined. RSP stays within 256 bytes below entry RSP. At the default seed `0xB0D1` the 36 exports have 110 mid-body `SUB RSP`, 77 mid-body `ADD RSP`, 52 mid-body `PUSH` and 13 mid-body `POP`, 11 branches, 10 calls, 6 `LEAVE` epilogues, 362 `[RSP+d]` and 72 `[RBP+d]` operands, and 168 reloads; 123 of the reloads and `POP` instructions read bytes stored at another RSP. Four negative controls in the same DLL are translated one at a time, and the test fails unless each is refused for its own reason: a reload of bytes that `ADD RSP` released and `SUB RSP` allocated again (`undefined stack byte`), a branch after which the two paths reach the join at different depths (`stack depth differs at join`), a read below RSP (`stack access below RSP`) and `SUB RSP, 4` (`unsupported stack adjustment`). The planted translator fault, `--mutant` (`stale_rsp`), resolves every `[RSP+d]` operand against the RSP that the prologue's allocation leaves, as if no later `SUB`, `ADD`, `PUSH` or `POP` had moved RSP; `PUSH`, `POP`, `[RBP+d]` operands and the frame proof are unchanged, and an operand whose moved bytes would leave the frame array keeps its index. The test fails unless that build differs from native. Measured on Windows 11 build 26300 with MSVC 19.51 (Visual Studio Build Tools, toolset 14.51) and ML64 14.51: at the default seed, 22,536 native, default and `/O2` comparisons matched in the `dev` and `release` presets, the four controls were refused, and the planted fault differed in 9,045 of 11,268 calls, in 31 of the 36 exports. The other five are two anchored exports that read through RBP and three calling exports whose moved operands would leave the frame array, where the fault keeps the index. Passing the clean translation as `--mutant` fails with `the planted translator fault was not detected`, and passing the mutant as the translation fails at the first mismatch with the reproduction command. Seeds `0x1`, `0x2`, `0xBEEF` and `0xCCD1` at 120 exports each made 75,120 comparisons with no refusal and no mismatch; the planted fault differed in 28,393, 30,027, 29,171 and 31,033 of 37,560 calls. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_rsp$' -V`. `CPU_FUZZ_RSP_SEED` and `CPU_FUZZ_RSP_FUNCTIONS` select a longer run. The generator does not use `MOV RSP, RBP`, `LEA RSP` or `ENTER` (the translator refuses them as a dynamic frame), an RBP anchor that moves after the prologue, stack arguments, calls in an anchored frame or fault equivalence. + ## Mesh draw fallback The bounded mesh translator can emit `cs_6_0` entry `main` and `vs_6_0` entry diff --git a/tools/fuzz_cpu.py b/tools/fuzz_cpu.py index a961514b3..73d6e7b03 100644 --- a/tools/fuzz_cpu.py +++ b/tools/fuzz_cpu.py @@ -1079,10 +1079,388 @@ def fp_inputs(seed, kinds): return values +# Mid-body RSP changes: functions whose RSP moves after the prologue, by SUB and ADD RSP, by PUSH and POP of a +# saved register that holds data, differently in the two arms of a branch, around a direct call, and below an RBP +# anchor that LEAVE or POP RBP releases. Each export is fn(x, y, out) with x in RCX, y in RDX and the output +# buffer in R8. cpu_switch_aot gives every [RSP+d] and [RBP+d] operand a constant index into one frame array, +# so a value stored at one depth and read back at another, through either base, must reach the same bytes. +RSP_SHAPES = ("adjust", "push", "branch", "call", "anchor_leave", "anchor_pop") +RSP_STEPS = (8, 16, 24, 32, 40, 48) +# RSP stays within 256 bytes below entry RSP. +RSP_DEEPEST = -0x100 +# Output words 0 to 19 take reloaded values and call results, the words from RSP_REGISTERS on the saved +# registers' final values, and each call's callee writes its own word from RSP_CALLEE on. +RSP_LOADS = 20 +RSP_MIN_LOADS = 4 +RSP_REGISTERS = 0xA0 +RSP_CALLEE = 0xC0 +# Each shape: the weight of every body operation, and the operations that it makes at least once. +RSP_WEIGHTS = { + "adjust": ({"store": 3, "load": 3, "rmw": 1, "grow": 2, "shrink": 2}, ()), + "push": ({"store": 2, "load": 3, "push": 3, "pop": 3, "grow": 1, "shrink": 1}, ("push",)), + "branch": ({"store": 2, "load": 2, "rmw": 1, "grow": 1, "shrink": 1, "push": 1, "pop": 1}, ("branch",)), + "call": ({"store": 2, "load": 2, "grow": 1, "shrink": 1}, ("call",)), + "anchor_leave": ({"store": 3, "load": 3, "rmw": 1, "grow": 2, "shrink": 1, "push": 1, "pop": 1}, ("grow",)), + "anchor_pop": ({"store": 3, "load": 3, "rmw": 1, "grow": 2, "shrink": 1, "push": 1, "pop": 1}, ("grow",)), +} +# Negative controls: a body after a 16-byte allocation that the translator must refuse, and the reason it must give. +RSP_CONTROLS = { + "released": (["sub rsp, 16", "mov QWORD PTR [rsp], rcx", "add rsp, 16", "sub rsp, 16", "mov rax, QWORD PTR [rsp]", + "add rsp, 16"], "undefined stack byte"), + "join": (["test cl, 1", "jz {name}_join", "sub rsp, 8", "{name}_join:", "mov QWORD PTR [rsp], rdx", "mov rax, rdx"], + "stack depth differs at join"), + "below": (["sub rsp, 16", "mov QWORD PTR [rsp], rcx", "add rsp, 16", "mov rax, QWORD PTR [rsp-8]"], + "stack access below RSP"), + "unaligned": (["sub rsp, 4", "mov DWORD PTR [rsp], ecx", "add rsp, 4", "mov rax, rcx"], + "unsupported stack adjustment"), +} + + +class RspBuilder: + """Emits one function whose RSP moves after the prologue, and follows which stack bytes hold a defined + value, so that it reads only what cpu_switch_aot accepts: a read needs each byte written on every path, and + the bytes that ADD RSP and POP leave below RSP, and the callee's home space after a call, are undefined. + + Offsets are from entry RSP. The prologue pushes one to three saved registers (and RBP for an anchored + shape) and allocates 16 to 48 bytes; the body may use that allocation, the caller's home space and what it + allocates itself, but never the pushed slots or the return address. Every saved register is overwritten + from the arguments before it is read, and the body pushes and pops only those registers.""" + + def __init__(self, name, rng, shape, callees): + self.name, self.rng, self.shape, self.callees = name, rng, shape, callees + self.prolog, self.lines, self.used = [], [], [] + self.saved = rng.sample(NONVOLATILE, 3 if shape == "call" else rng.choice((1, 2, 3))) + for register in self.saved: + self.prolog += [f"push {register}", f".pushreg {register}"] + pushed = 8 * len(self.saved) + self.anchor = None + if shape.startswith("anchor"): + pushed += 8 + self.anchor = -pushed + self.prolog += ["push rbp", ".pushreg rbp", "mov rbp, rsp", ".setframe rbp, 0"] + self.size = rng.choice((16, 24, 32, 40, 48)) + self.prolog += [f"sub rsp, {self.size}", f".allocstack {self.size}"] + # RSP after the prologue; the body never releases bytes above it. + self.floor = self.depth = -pushed - self.size + self.blocked = set(range(-pushed, 8)) + self.defined, self.stored_at = set(), {} + # A caller keeps its output pointer in a saved register, because the call overwrites R8. + self.out = self.saved[0] if shape == "call" else "r8" + self.data = [register for register in self.saved if register != self.out] + self.arguments = True # RCX and RDX still hold x and y + self.slots = self.labels = self.calls = self.loads = 0 + self.cross = 0 # reloads of bytes stored at another RSP + + def emit(self, line): + self.lines.append(line) + + def state(self): + return self.depth, set(self.defined), dict(self.stored_at) + + def restore(self, state): + self.depth, self.defined, self.stored_at = state[0], set(state[1]), dict(state[2]) + + def operand(self, offset, width): + """[RSP+d] at the current RSP or, in an anchored function, often [RBP+d] for the same bytes.""" + if self.anchor is not None and self.rng.random() < 0.5: + return f"{PTR[width]} [rbp{offset - self.anchor:+d}]" + return f"{PTR[width]} [rsp+{offset - self.depth}]" + + def sources(self): + return [*self.data, *(("rcx", "rdx") if self.arguments else ()), "rax"] + + def release(self, low, high): + for offset in range(low, high): + self.defined.discard(offset) + self.stored_at.pop(offset, None) + + def spots(self, width, defined): + """Offsets where width bytes lie above RSP and below the end of the home space, outside the pushed + slots and the return address, and are all defined when defined is set.""" + found = [] + for offset in range(self.depth, 40 - width + 1): + span = range(offset, offset + width) + if any(byte in self.blocked for byte in span): + continue + if defined and not all(byte in self.defined for byte in span): + continue + found.append(offset) + return found + + def store(self): + width = self.rng.choice((1, 2, 4, 8)) + spots = self.spots(width, False) + if not spots: + return False + # Mostly near RSP, where a later ADD RSP or POP releases the bytes and a deeper RSP reads them back. + near = [offset for offset in spots if offset < self.depth + 24] + at = self.rng.choice(near if near and self.rng.random() < 0.6 else spots) + if self.rng.random() < 0.2: + source = self.rng.choice((0x5A, 0x7F, 0x81, 0x33)) + else: + source = part(self.rng.choice(self.sources()), width) + self.emit(f"mov {self.operand(at, width)}, {source}") + for byte in range(at, at + width): + self.defined.add(byte) + self.stored_at[byte] = self.depth + return True + + def load(self): + # Room is kept for the forced cross-depth reload and two call results. + if self.slots >= RSP_LOADS - 3: + return False + width = self.rng.choice((1, 2, 4, 8)) + spots = self.spots(width, True) + if not spots: + return False + cross = [offset for offset in spots + if any(self.stored_at[byte] != self.depth for byte in range(offset, offset + width))] + at = self.rng.choice(cross if cross and self.rng.random() < 0.8 else spots) + self.cross += at in cross + self.loads += 1 + operand, signed = self.operand(at, width), self.rng.random() < 0.5 + if width == 8: + self.emit(f"mov r10, {operand}") + elif width == 4: + self.emit(f"movsxd r10, {operand}" if signed else f"mov r10d, {operand}") + else: + self.emit(f"{'movsx r10' if signed else 'movzx r10d'}, {operand}") + self.result("r10") + return True + + def result(self, register): + self.emit(f"mov QWORD PTR [{self.out}+{8 * self.slots}], {register}") + self.slots += 1 + if register != "rax": + self.emit(self.rng.choice((f"xor rax, {register}", f"add rax, {register}", f"sub rax, {register}"))) + self.emit("rol rax, 7") + + def rmw(self): + width = self.rng.choice((1, 2, 4, 8)) + spots = self.spots(width, True) + if not spots: + return False + at = self.rng.choice(spots) + source = part(self.rng.choice(self.sources()), width) + self.emit(f"{self.rng.choice(('add', 'xor', 'sub'))} {self.operand(at, width)}, {source}") + for byte in range(at, at + width): + self.stored_at[byte] = self.depth + return True + + def grow(self, steps=RSP_STEPS): + steps = [step for step in steps if self.depth - step >= RSP_DEEPEST] + if not steps: + return False + step = self.rng.choice(steps) + self.emit(f"sub rsp, {step}") + self.depth -= step + return True + + def shrink(self): + room = self.floor - self.depth + if not room: + return False + step = room if self.rng.random() < 0.4 else self.rng.choice(range(8, room + 1, 8)) + self.emit(f"add rsp, {step}") + self.release(self.depth, self.depth + step) + self.depth += step + return True + + def push(self): + if not self.data or self.depth - 8 < RSP_DEEPEST: + return False + self.emit(f"push {self.rng.choice(self.data)}") + self.depth -= 8 + for byte in range(self.depth, self.depth + 8): + self.defined.add(byte) + self.stored_at[byte] = self.depth + return True + + def pop(self): + if (not self.data or self.depth >= self.floor + or not all(byte in self.defined for byte in range(self.depth, self.depth + 8))): + return False + self.cross += any(self.stored_at[byte] != self.depth for byte in range(self.depth, self.depth + 8)) + self.emit(f"pop {self.rng.choice(self.data)}") + self.release(self.depth, self.depth + 8) + self.depth += 8 + return True + + def straight(self): + """A store, a reload or an in-place update at the current RSP.""" + for _ in range(12): + if getattr(self, self.rng.choice(("store", "store", "load", "load", "rmw")))(): + return + + def branch(self): + """A TEST and a conditional jump on a saved register, and two arms that move RSP by the same amount in + different ways (SUB RSP or PUSH, with or without a balanced excursion), so the join sees one depth. + A byte that only one arm defines is undefined after the join.""" + if not self.data: + return False + drops = [drop for drop in (0, 8, 16, 24) if self.depth - drop - 48 >= RSP_DEEPEST] + if not drops: + return False + self.labels += 1 + other, join = f"{self.name}_other{self.labels}", f"{self.name}_join{self.labels}" + self.emit(f"test {part(self.rng.choice(self.data), 1)}, {self.rng.choice((1, 2, 4))}") + self.emit(f"j{self.rng.choice(('z', 'nz'))} {other}") + drop, start, outcomes = self.rng.choice(drops), self.state(), [] + for arm in (0, 1): + self.restore(start) + if arm: + self.emit(f"{other}:") + target = self.depth - drop + self.straight() + while self.depth > target: + if self.depth - 8 == target or self.rng.random() < 0.4: + self.push() + else: + self.grow([step for step in RSP_STEPS if self.depth - step >= target]) + if self.rng.random() < 0.6: + self.straight() + if self.rng.random() < 0.3: + # An excursion that the arm releases again before the join. + step = self.rng.choice((8, 16, 32)) + self.emit(f"sub rsp, {step}") + self.depth -= step + self.straight() + self.straight() + self.emit(f"add rsp, {step}") + self.release(self.depth, self.depth + step) + self.depth += step + outcomes.append(self.state()) + if not arm: + self.emit(f"jmp {join}") + self.emit(f"{join}:") + self.defined = outcomes[0][1] & outcomes[1][1] + self.stored_at = {byte: min(outcome[2][byte] for outcome in outcomes) for byte in self.defined} + return True + + def call(self): + """A mid-body SUB RSP that leaves RSP 16-byte aligned with room for the callee's home space, a direct + call, and the callee's result in RAX. After the call the volatile registers and the 32 bytes at RSP are + undefined; the rest of the frame is kept.""" + first = (self.depth - 8) % 16 + step = first + 16 * self.rng.choice((1, 2) if not first else (0, 1, 2)) + if self.depth - step < RSP_DEEPEST: + return False + self.emit(f"sub rsp, {step}") + self.depth -= step + callee = self.rng.choice(self.callees) + if callee not in self.used: + self.used.append(callee) + x, y = self.rng.choice((*self.data, "rax")), self.rng.choice(self.data) + self.emit(f"mov rcx, {x}") + self.emit(f"lea rdx, [{y}+{self.rng.randrange(1, 0x8000)}]") + self.emit(f"lea r8, [{self.out}+{RSP_CALLEE + 8 * self.calls}]") + self.emit(f"call {callee.name}") + self.calls += 1 + self.arguments = False + self.release(self.depth, self.depth + 32) + self.result("rax") + return True + + def operation(self, name): + return getattr(self, name)() + + def cross_depth(self): + """A store at the current RSP, a move of RSP and a reload of those bytes at the new RSP.""" + if self.depth - 8 < RSP_DEEPEST: + self.emit(f"add rsp, {self.floor - self.depth}") + self.release(self.depth, self.floor) + self.depth = self.floor + width = self.rng.choice((2, 4, 8)) + at = self.rng.choice(self.spots(width, False)) + self.emit(f"mov {self.operand(at, width)}, {part(self.rng.choice(self.sources()), width)}") + for byte in range(at, at + width): + self.defined.add(byte) + self.stored_at[byte] = self.depth + self.grow([step for step in RSP_STEPS if self.depth - step >= RSP_DEEPEST] or [8]) + self.cross += 1 + self.loads += 1 + operand = self.operand(at, width) + self.emit(f"mov r10, {operand}" if width == 8 else f"movzx r10d, {operand}" if width == 2 + else f"mov r10d, {operand}") + self.result("r10") + + def build(self): + rng = self.rng + if self.out != "r8": + self.emit(f"mov {self.out}, r8") + for register in self.data: + self.emit(rng.choice((f"mov {register}, rcx", f"mov {register}, rdx", f"lea {register}, [rcx+rdx*2]", + f"lea {register}, [rdx+rcx*4+7]"))) + self.emit(rng.choice((f"xor {register}, rdx", f"rol {register}, 13", f"add {register}, rcx"))) + self.emit("mov rax, rcx") + for _ in range(rng.randint(2, 4)): + self.store() + weights, required = RSP_WEIGHTS[self.shape] + names = list(weights) + operations = [rng.choices(names, [weights[name] for name in names])[0] for _ in range(rng.randint(6, 12))] + for name in required * rng.choice((1, 2)): + operations.insert(rng.randrange(len(operations) + 1), name) + for name in operations: + if not self.operation(name): + for _ in range(12): + if self.operation(rng.choices(names, [weights[name] for name in names])[0]): + break + if not self.cross: + self.cross_depth() + for _ in range(48): + if self.loads >= RSP_MIN_LOADS: + break + # More reloads at the final RSP, after a store when nothing is defined. + self.load() or self.store() + for slot, register in enumerate(self.data): + self.emit(f"mov QWORD PTR [{self.out}+{RSP_REGISTERS + 8 * slot}], {register}") + if self.shape == "anchor_leave": + # LEAVE restores RSP from the anchor, so the body may end below the prologue's RSP. + self.emit("leave") + else: + while self.depth < self.floor: + if not (rng.random() < 0.4 and self.pop()): + self.shrink() + self.emit(f"add rsp, {self.size}") + if self.anchor is not None: + self.emit("pop rbp") + self.lines += [f"pop {register}" for register in reversed(self.saved)] + self.emit("ret") + return Function(self.name, self.lines, self.prolog, self.used) + + +def rsp_callee(name, index): + """A frameless callee that only the generated callers reach: it writes one word through R8 and returns a + value that is not symmetric in RCX and RDX.""" + if index == 0: + lines = ["lea rax, [rcx+rdx*2]", "xor rax, 5A5Ah", "mov QWORD PTR [r8], rax", "rol rax, 5", "ret"] + else: + lines = ["mov rax, rdx", "sub rax, rcx", "mov DWORD PTR [r8+4], eax", "imul rax, rax, 7", "ret"] + return Function(name, lines, export=False) + + +def rsp_control(name, kind): + """A negative control: a mid-body RSP change that the translator must refuse.""" + body, reason = RSP_CONTROLS[kind] + lines = [*(line.format(name=name) for line in body), "mov QWORD PTR [r8], rax", "add rsp, 16", "ret"] + return Function(name, lines, ["sub rsp, 16", ".allocstack 16"], refused=reason) + + +def generate_rsp(seed, count): + """Exports whose RSP moves after the prologue, cycling through six shapes, then four refused controls. + + Two frameless callees, which no export names, serve the calling shape.""" + rng = random.Random(seed) + callees = [rsp_callee(f"fuzz_rsp_callee_{index}", index) for index in range(2)] + functions = [RspBuilder(f"fuzz_rsp_{index}", rng, RSP_SHAPES[index % len(RSP_SHAPES)], callees).build() + for index in range(count)] + return [*callees, *functions, *(rsp_control(f"fuzz_rsp_refused_{kind}", kind) for kind in RSP_CONTROLS)] + + AREAS = {"leaf": (generate, "cpu_fuzz"), "frames": (generate_frames, "cpu_fuzz_frames"), "calls": (generate_calls, "cpu_fuzz_calls"), "chains": (generate_chains, "cpu_fuzz_chains"), "switches": (generate_switches, "cpu_fuzz_switches"), - "scalar_fp": (generate_scalar_fp, "cpu_fuzz_scalar_fp")} + "scalar_fp": (generate_scalar_fp, "cpu_fuzz_scalar_fp"), "rsp": (generate_rsp, "cpu_fuzz_rsp")} def inputs_for(seed, area="leaf", signature=None): @@ -1378,9 +1756,46 @@ def plant_minmax_swap(cpu_sse_aot, image, functions): extrema[low], extrema[high] = extrema[high], extrema[low] +def plant_stale_rsp(cpu_switch_aot, image, functions): + """Resolve every [RSP+d] operand against the RSP that the prologue's allocation leaves (after the first + SUB RSP in address order), as if no later SUB, ADD, PUSH or POP had moved RSP. + + This is a planted translator fault for the negative control: the frame proof, PUSH, POP and every + [RBP+d] operand are unchanged, but a value stored at one RSP and read back at another reaches other + frame bytes. An operand whose moved bytes would leave the frame array keeps its index. + """ + from iced_x86 import Mnemonic as M, MemorySizeExt, Register as R + + shifts = {} # RVA -> (RSP at the instruction minus RSP after the prologue, bytes of the frame array) + original_frame = cpu_switch_aot.Frame.__init__ + + def frame_init(self, function, edges): + original_frame(self, function, edges) + if self.adjustments: + floor = self.offsets[function.instructions[min(self.adjustments)].next_ip] + for ip, offset in self.offsets.items(): + if offset != floor and ip in self.accesses: + shifts[ip] = (offset - floor, self.size) + + original_slot = cpu_switch_aot.Lifter.slot + + def slot(self, ins): + text = original_slot(self, ins) + if ins.ip in shifts and ins.memory_base == R.RSP and ins.mnemonic not in (M.PUSH, M.POP): + shift, size = shifts[ins.ip] + index = self.frame[ins.ip] + if 0 <= index - shift <= size - MemorySizeExt.size(ins.memory_size): + text = text.replace(f"frame + {index})", f"frame + {index - shift})") + return text + + cpu_switch_aot.Frame.__init__ = frame_init + cpu_switch_aot.Lifter.slot = slot + + MUTANTS = {"frames": ("reload_shift", plant_reload_shift), "calls": ("call_retarget", plant_call_retarget), "chains": ("swapped_arguments", plant_swapped_arguments), - "switches": ("table_rotate", plant_table_rotate), "scalar_fp": ("minmax_swap", plant_minmax_swap)} + "switches": ("table_rotate", plant_table_rotate), "scalar_fp": ("minmax_swap", plant_minmax_swap), + "rsp": ("stale_rsp", plant_stale_rsp)} def translate(seed, count, image, output, area="leaf", mutant=False): From dc16b29bed3895a675a2b1205c6423820f0ff23a Mon Sep 17 00:00:00 2001 From: denn0x <55638248+denn0x@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:13:15 +0000 Subject: [PATCH 009/775] startup: read the whole destination page array when a storage request runs Requests with page destinations captured the title's page tokens at enqueue and refreshed only entries that were still zero. The title also replaces non-zero entries between enqueue and execution, so data went to pages it had already reassigned. The array is now read in full when the request runs; replaced entries are counted in the heartbeat. Measured on a local run: 48,222 tokens replaced after enqueue by 200 s. Before the change those writes landed in stale pages and loading ended in crashes on corrupted pointers at 187-212 s; with it, loading continues past that point. AI-assisted (Claude Code). --- docs/startup-runtime.md | 5 +++-- src/startup_stubs/xcrdapi.cpp | 15 ++++++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index efff6ec2f..7da04a718 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -266,8 +266,9 @@ These are measured on one executable; treat them as hypotheses for others. the second is a GPU view of the first. Mapping each page's section into both views makes those resources readable; without it, a YUV video shows a solid green screen (all-zero planes). - **DirectStorage ordering.** Requests must run after `Submit`, in order with status and fence - entries. Titles fill destination page-array entries after `EnqueueRequest`; an entry that is 0 - at enqueue is read again when the request runs. + entries. Titles fill destination page-array entries after `EnqueueRequest`, and also replace + entries filled earlier, so the whole page array is read again when the request runs. The + heartbeat counts entries replaced after enqueue. - **Sub-dword addressing (SDWA).** The translator lowers the byte and word selects of the 32-bit integer VOP1/VOP2 SDWA forms: a source selection is zero-extended, or sign-extended under `sext()`, and the low bits of the result are placed in the destination field, with `UNUSED_PAD` zeroing the diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index dd86f0325..9c139ae9b 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -316,7 +316,7 @@ long __stdcall file_information(Object* self, BY_HANDLE_FILE_INFORMATION* info) // or memory pointer), +0x28 source offset, +0x30 source size (u32). Uncompressed requests are executed // synchronously; compressed ones are logged and left undone. The first requests are logged in full. LONG requests_done, requests_compressed, requests_failed, requests_bcpack_blank; -LONG zero_tokens_at_enqueue, zero_tokens_at_run; +LONG zero_tokens_at_enqueue, zero_tokens_at_run, tokens_replaced_after_enqueue; void execute_request(Object* self, const unsigned char* request, const ULONG_PTR* tokens, u64 entry_id, u64 submission_id) { if (!request) return; @@ -568,9 +568,14 @@ void run_entry(Object* self, Entry& entry) const u64 options = *reinterpret_cast(entry.bytes); if ((options & (1ull << 21)) && !entry.tokens.empty()) { const auto* title = *reinterpret_cast(entry.bytes + 0x08); + // The title's page array is read again in full when the request runs: entries are filled, + // and also replaced, after enqueue. Writing through a token captured at enqueue put data + // into a page the title had already reassigned. for (std::size_t i = 0; i < entry.tokens.size(); ++i) - if (!entry.tokens[i] && title && x2w_local::readable(title + i, sizeof(ULONG_PTR))) { - entry.tokens[i] = title[i]; + if (title && x2w_local::readable(title + i, sizeof(ULONG_PTR))) { + const ULONG_PTR now = title[i]; + if (entry.tokens[i] && now != entry.tokens[i]) InterlockedIncrement(&tokens_replaced_after_enqueue); + entry.tokens[i] = now; if (!entry.tokens[i]) InterlockedIncrement(&zero_tokens_at_run); } } @@ -854,8 +859,8 @@ extern "C" long __stdcall DStorageGetFactory(const GUID* riid, void** out) // Heartbeat preserves "inflated=%ld" format string for tools/startup/live_view.py; // requests_compressed counts all compressed streams (zlib and standalone/embedded BCPack). log("x2w-dstorage heartbeat %d s: requests done=%ld inflated=%ld failed=%ld bcpack-blank=%ld; page tokens 0 at enqueue=%ld, " - "still 0 at run=%ld; %s, live physical-page sections=%s", second, requests_done, requests_compressed, - requests_failed, requests_bcpack_blank, zero_tokens_at_enqueue, zero_tokens_at_run, memory, + "still 0 at run=%ld, replaced after enqueue=%ld; %s, live physical-page sections=%s", second, requests_done, requests_compressed, + requests_failed, requests_bcpack_blank, zero_tokens_at_enqueue, zero_tokens_at_run, tokens_replaced_after_enqueue, memory, section_text); last = total2; last_memory = sample; From 7b6e589675219861e466e1e319283e872cf35ee7 Mon Sep 17 00:00:00 2001 From: Maxim Trusov <146969829+Maxim-Root@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:56:03 +0300 Subject: [PATCH 010/775] shader: accept v_cmpx_class_f32 as a pixel_aot region opener The v_cmpx region opener (#932, #1335) accepted VOPC e32 compares on binary32 and integers; class forms were left for later. Accept v_cmpx_class_f32_e32 and lower it like the e32 v_cmp_class_f32, on the raw binary32 encoding of src0 and the class mask in VSRC1. The e64 and SDWA spellings, an SGPR VSRC1, source modifiers and the f16/f64 class forms stay refused. Draws: the +normal class of s44 - sample.x opens the ramp region on mixed, full and empty masks through both restores, with -normal and mask-free mutants; four uniform class regions on +inf, a quiet NaN, -0 and a positive denormal, each with a flipped-channel wrong reference. The LLVM 15 round trip covers the three programs, and form_coverage_check counts 61 v_cmpx forms. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 4 +- tests/form_coverage_check.py | 12 ++--- tests/pixel_aot_check.py | 86 ++++++++++++++++++++++++++++++++++-- tools/pixel_aot.py | 10 ++++- 4 files changed, 100 insertions(+), 12 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 2f635c723..0173d695e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -708,9 +708,9 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^pixel_aot_exec_regions_(warp|hardware)$' -V ``` -The same region can also open with `s_mov_b64 s[a:b], exec` immediately followed by a VOPC `_e32` `v_cmpx` on binary32 or 16-, 32- or 64-bit integer operands (issue #932): all 16 binary32 predicates, the 8 signed and 8 unsigned integer predicates at 32 and 64 bits and the 6 signed and 6 unsigned ones at 16 bits (gfx10 has no 16-bit `f` or `t`), 60 forms. A 16-bit comparison reads the low 16 bits of each operand, and a 64-bit one takes the VGPR-pair, SGPR-pair and inline-constant sources of the 64-bit `v_cmp` with a VGPR pair as VSRC1. The [AMD RDNA 2 ISA guide](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) (§6.2.2, §12.9) defines `v_cmpx` as writing its comparison to EXEC, and a thread writes only while its EXEC bit is set. From the known entry mask the translator therefore takes the new mask as the entry mask intersected with the comparison, the same lane condition as `v_cmp` plus `s_and_saveexec_b64`. That intersection rule comes from the ISA text and from LLVM's gfx10.3 rewrite of `v_cmp` plus `s_and_saveexec` into this pattern; no gfx1013 hardware run checks it. The save must hold the entry mask (not a whole-quad mask), must directly precede the `v_cmpx` and must not overlap a pending scalar load, and the region closes with `s_mov_b64 exec, s[a:b]` or `s_or_b64 exec, exec, s[a:b]` on the saved pair; the optional `s_cbranch_execz` must sit right after the `v_cmpx` and target that restore. `v_cmpx` writes neither VCC nor SCC, so both keep their tracked values through the region; `s_mov_b64` leaves SCC, while `s_or_b64` writes it from the restored mask, which is untracked, so an SCC reader after the `s_or_b64` close rejects. The region body follows the rules above. `_e64`, SDWA, binary16, binary64 and class forms, a VSRC1 that is not a VGPR (a VGPR pair at 64 bits), source modifiers, chained or nested `v_cmpx`, wave32 saves and kill shapes all reject; the else transition follows the rules above. +The same region can also open with `s_mov_b64 s[a:b], exec` immediately followed by a VOPC `_e32` `v_cmpx` on binary32 or 16-, 32- or 64-bit integer operands (issue #932): all 16 binary32 predicates, the 8 signed and 8 unsigned integer predicates at 32 and 64 bits and the 6 signed and 6 unsigned ones at 16 bits (gfx10 has no 16-bit `f` or `t`), and `v_cmpx_class_f32`, 61 forms. `v_cmpx_class_f32` tests the class of the raw binary32 encoding of src0 against the class mask in VSRC1, as the e32 `v_cmp_class_f32` does. A 16-bit comparison reads the low 16 bits of each operand, and a 64-bit one takes the VGPR-pair, SGPR-pair and inline-constant sources of the 64-bit `v_cmp` with a VGPR pair as VSRC1. The [AMD RDNA 2 ISA guide](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) (§6.2.2, §12.9) defines `v_cmpx` as writing its comparison to EXEC, and a thread writes only while its EXEC bit is set. From the known entry mask the translator therefore takes the new mask as the entry mask intersected with the comparison, the same lane condition as `v_cmp` plus `s_and_saveexec_b64`. That intersection rule comes from the ISA text and from LLVM's gfx10.3 rewrite of `v_cmp` plus `s_and_saveexec` into this pattern; no gfx1013 hardware run checks it. The save must hold the entry mask (not a whole-quad mask), must directly precede the `v_cmpx` and must not overlap a pending scalar load, and the region closes with `s_mov_b64 exec, s[a:b]` or `s_or_b64 exec, exec, s[a:b]` on the saved pair; the optional `s_cbranch_execz` must sit right after the `v_cmpx` and target that restore. `v_cmpx` writes neither VCC nor SCC, so both keep their tracked values through the region; `s_mov_b64` leaves SCC, while `s_or_b64` writes it from the restored mask, which is untracked, so an SCC reader after the `s_or_b64` close rejects. The region body follows the rules above. `_e64`, SDWA, binary16 and binary64 forms (including their class tests), a VSRC1 that is not a VGPR (a VGPR pair at 64 bits), source modifiers, chained or nested `v_cmpx`, wave32 saves and kill shapes all reject; the else transition follows the rules above. -The fixtures draw the ramp region with the `s_mov_b64` restore, the `s_or_b64` restore and the skip on mixed (0.5), full (10) and empty (-1) masks, and each must match all 64 pixels; a reversed predicate and a mask-free copy of the body must mismatch on the mixed mask. A second program sets VCC and SCC before the region and reads both after the `s_mov_b64` close; references that take VCC from the `v_cmpx` comparison or invert SCC must mismatch. Twelve programs of four regions each draw every accepted predicate against the truth tables of the existing `v_cmp` draws (less, equal, greater and, for binary32, unordered inputs), alternating the two restores; the signed shader against the unsigned truth table must mismatch. The 16-bit operand pairs have high halves that disagree with their low halves, so a signed 16-bit reference read as unsigned or over all 32 bits must mismatch. Four more programs run each 64-bit predicate over the operand shapes and word patterns of the 64-bit `v_cmp` draws against the same reference, and the signed shader against the unsigned reference must mismatch. Every fixture is also assembled and disassembled with LLVM 15 for gfx1013 and must lower identically. The translation controls cover the rejections listed above, wrong skip targets, an overwritten save pair and unsupported body instructions. +The fixtures draw the ramp region with the `s_mov_b64` restore, the `s_or_b64` restore and the skip on mixed (0.5), full (10) and empty (-1) masks, and each must match all 64 pixels; a reversed predicate and a mask-free copy of the body must mismatch on the mixed mask. A second program sets VCC and SCC before the region and reads both after the `s_mov_b64` close; references that take VCC from the `v_cmpx` comparison or invert SCC must mismatch. Twelve programs of four regions each draw every accepted predicate against the truth tables of the existing `v_cmp` draws (less, equal, greater and, for binary32, unordered inputs), alternating the two restores; the signed shader against the unsigned truth table must mismatch. The 16-bit operand pairs have high halves that disagree with their low halves, so a signed 16-bit reference read as unsigned or over all 32 bits must mismatch. Four more programs run each 64-bit predicate over the operand shapes and word patterns of the 64-bit `v_cmp` draws against the same reference, and the signed shader against the unsigned reference must mismatch. Two more programs open the ramp region with `v_cmpx_class_f32_e32` on the +normal class of `s44 - sample.x`, which holds exactly where `s44 > sample.x`. Through both restores, they must match the same masked pixels on the mixed, full and empty masks. The -normal mask (the reversed region) and a mask-free body must mismatch. A fourth program opens four uniform class regions on the inputs of the `v_cmp_class_f32` draw: +inf against its own bit, a quiet NaN against both NaN bits, -0 against the +0 bit and a positive denormal against its bit. A wrong result in any channel must mismatch. Every fixture is also assembled and disassembled with LLVM 15 for gfx1013 and must lower identically. The translation controls cover the rejections listed above, wrong skip targets, an overwritten save pair and unsupported body instructions. ```powershell cmake --build --preset dev --target offscreen_check diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 4ce0cc669..7c8e349e1 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -404,15 +404,17 @@ def check_shader_records(): # Each name is counted once as VOPC and once as VOP3; the five sets must not share a name. assert len(compare_forms) == 2 * (len(narrow_int) + len(int64) + len(f16_compares) + len(f32_compares) + len(f64_compares)), len(compare_forms) - # VOPC e32 regions support binary32 and integer predicates, but not binary16, binary64 or classes. - compare_neighbours = {"v_cmpx_lt_f16", "v_cmpx_lt_f64", "v_cmpx_class_f32", "v_cmpx_class_f64"} - # v_cmpx regions (issue #932): every binary32 and integer predicate counts in VOPC (e32) only. + # VOPC e32 regions support binary32 and integer predicates and the binary32 class test, but not binary16, + # binary64 or their class tests. + compare_neighbours = {"v_cmpx_lt_f16", "v_cmpx_lt_f64", "v_cmpx_class_f16", "v_cmpx_class_f64"} + # v_cmpx regions (issue #932): every binary32 and integer predicate and v_cmpx_class_f32 count in VOPC (e32) only. cmpx_forms = ({("VOPC", f"v_cmpx_{op}_f32") for op in pixel.PREDICATES} | {("VOPC", f"v_cmpx_{op}_{kind}") for op in pixel.INT_PREDICATES for kind in ("i32", "u32", "i64", "u64")} | {("VOPC", f"v_cmpx_{op}_{kind}") for op in ("eq", "ne", "lt", "le", "gt", "ge") - for kind in ("i16", "u16")}) - assert len(cmpx_forms) == 60, len(cmpx_forms) + for kind in ("i16", "u16")} + | {("VOPC", "v_cmpx_class_f32")}) + assert len(cmpx_forms) == 61, len(cmpx_forms) for name in ("gfx1013.tsv", "rdna2.tsv"): reference = fc.load_reference(name) assert compare_forms | {("VOPC", n) for n in compare_neighbours} <= reference, name diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 9adf6a5a3..2403950e2 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -803,6 +803,35 @@ def cmpx64_group(kind, group): return cmp64_program(body) +# v_cmpx_class_f32 regions: the class of the raw binary32 src0 in the class mask in VSRC1 opens the region. +# v20 = s44 - sample.x is a positive normal value exactly where s44 > sample.x: the ramp never equals the thresholds +# and no difference is subnormal, so under the +normal mask (0x100) the region selects the lanes masked_pixels expects. +CMPX_CLASS_COMPARE = "v_cmpx_class_f32_e32 v20, v21" +CMPX_CLASS_POSITIVE_NORMAL = 0x100 + + +def cmpx_class_region(restore=CMPX_MOV_RESTORE, classes=CMPX_CLASS_POSITIVE_NORMAL, compare=CMPX_CLASS_COMPARE): + """The v_cmpx region with a class opener: while s44 - sample.x is in `classes`, overwrite v13 and v14.""" + return uncompressed_export(["v_sub_f32_e64 v20, s44, v12", f"v_mov_b32_e32 v21, {classes:#x}", CMPX_SAVE, + compare, "v_mov_b32_e32 v13, s45", "v_mov_b32_e32 v14, s46", restore]) + + +# Four uniform class regions on CLASS_BITS, as in the v_cmp_class_f32 draw: +inf against its own bit, a quiet NaN +# against both NaN bits, -0 against the +0 bit and a positive denormal against its bit. The class mask is a VGPR +# (VSRC1 of VOPC e32), and the regions alternate the two restores. +CMPX_CLASS_MASKS = (0x200, 3, 0x40, 0x80) + + +def cmpx_class_group(masks=CMPX_CLASS_MASKS): + """Four v_cmpx_class_f32 regions, each setting one channel to 1.0 when s44+channel is in its class mask.""" + body = ["v_mov_b32_e32 v19, 1.0"] + [f"v_mov_b32_e32 v{12 + channel}, 0" for channel in range(4)] + for channel, classes in enumerate(masks): + body += [f"v_mov_b32_e32 v18, {classes if classes <= 64 else hex(classes)}", CMPX_SAVE, + f"v_cmpx_class_f32_e32 s{44 + channel}, v18", f"v_mov_b32_e32 v{12 + channel}, v19", + CMPX_MOV_RESTORE if channel % 2 == 0 else CMPX_OR_RESTORE] + return with_constants(body) + + def cmpx_observables(): """VCC and SCC written before a v_cmpx region keep their values after the s_mov_b64 restore. @@ -857,6 +886,45 @@ def check_cmpx_draw(directory, compiler, renderer, backend): case = directory / f"cmpx-{label}.case" write_case(case, constants, expected) run_pixel_batch(renderer, backend, shader, [(case, "mismatch")]) + # v_cmpx_class_f32 openers: the +normal class of s44 - sample.x on mixed, full and empty masks through both + # restores. The -normal mask (the reversed region) and a mask-free body must mismatch on the mixed mask. + for label, program in (("class-mov", cmpx_class_region()), ("class-or", cmpx_class_region(CMPX_OR_RESTORE))): + source.write_text(translate(program), encoding="ascii") + compile_shader(compiler, source, shader) + cases = [] + for threshold in (0.5, 10.0, -1.0): + struct.pack_into("<4f", constants, 12, threshold, 0.25, 0.75, 0.0) + case = directory / f"cmpx-{label}-{len(cases)}.case" + write_case(case, constants, masked_pixels(threshold, (0.25, 0.75), False)) + cases.append((case, "pass")) + run_pixel_batch(renderer, backend, shader, cases) + struct.pack_into("<4f", constants, 12, 0.5, 0.25, 0.75, 0.0) + class_unmasked = [line for line in cmpx_class_region() if line not in (CMPX_SAVE, CMPX_CLASS_COMPARE, + CMPX_MOV_RESTORE)] + for label, mutant in (("class-negative-normal", cmpx_class_region(classes=0x8)), + ("class-unmasked", class_unmasked)): + source.write_text(translate(mutant), encoding="ascii") + compile_shader(compiler, source, shader) + case = directory / f"cmpx-{label}.case" + write_case(case, constants, expected) + run_pixel_batch(renderer, backend, shader, [(case, "mismatch")]) + # Uniform class regions on +inf, a quiet NaN, -0 and a positive denormal: each channel's wrong result mismatches. + source.write_text(translate(cmpx_class_group()), encoding="ascii") + compile_shader(compiler, source, shader) + class_constants = bytearray(256) + struct.pack_into("<4I", class_constants, 12, *CLASS_BITS) + class_expected = [1.0, 1.0, 0.0, 1.0] + cases = [] + for k in range(4): + wrong = list(class_expected) + wrong[k] = 1.0 - wrong[k] + case = directory / f"cmpx-class-group-wrong-{k}.case" + case.write_bytes(class_constants + struct.pack("<4f", *wrong) * 64) + cases.append((case, "mismatch")) + case = directory / "cmpx-class-group.case" + case.write_bytes(class_constants + struct.pack("<4f", *class_expected) * 64) + cases.append((case, "pass")) + run_pixel_batch(renderer, backend, shader, cases) # VCC and SCC from before the region, on mixed, full and empty masks; SCC is 1 only for 0.5. source.write_text(translate(cmpx_observables()), encoding="ascii") compile_shader(compiler, source, shader) @@ -10880,13 +10948,19 @@ def selects(program): for kind in ("i64", "u64"): for group in (0, 1): assert selects(cmpx64_group(kind, group)) == 4 + for restore in (CMPX_MOV_RESTORE, CMPX_OR_RESTORE): + assert selects(cmpx_class_region(restore)) == 2 + assert selects(cmpx_class_group()) == 4 + assert translate(cmpx_class_group()).count("(class32(") == 4 # Each accepted comparison kind lowers like the v_cmp of the same kind. for compare, plain in (("v_cmpx_lt_f32_e32 s44, v12", "v_cmp_lt_f32_e32 vcc_lo, s44, v12"), ("v_cmpx_ge_i32_e32 v13, v12", "v_cmp_ge_i32_e32 vcc_lo, v13, v12"), ("v_cmpx_ne_u32_e32 0x3f000000, v12", "v_cmp_ne_u32_e32 vcc_lo, 0x3f000000, v12"), ("v_cmpx_nlg_f32_e32 -1.0, v12", "v_cmp_nlg_f32_e32 vcc_lo, -1.0, v12"), ("v_cmpx_gt_i16_e32 v13, v12", "v_cmp_gt_i16_e32 vcc_lo, v13, v12"), - ("v_cmpx_le_u16_e32 0x8000, v12", "v_cmp_le_u16_e32 vcc_lo, 0x8000, v12")): + ("v_cmpx_le_u16_e32 0x8000, v12", "v_cmp_le_u16_e32 vcc_lo, 0x8000, v12"), + ("v_cmpx_class_f32_e32 s44, v12", "v_cmp_class_f32_e32 vcc_lo, s44, v12"), + ("v_cmpx_class_f32_e32 0x200, v12", "v_cmp_class_f32_e32 vcc_lo, 0x200, v12")): expr = next(line for line in translate(cmpx_region(compare=compare)).splitlines() if "bool cmp" in line) reference = next(line for line in translate(uncompressed_export([plain])).splitlines() if "bool cmp" in line) assert expr.split(" = ", 1)[1] == reference.split(" = ", 1)[1], (compare, expr, reference) @@ -10936,13 +11010,17 @@ def selects(program): expect_value_error(translate, [CMPX_MOV_RESTORE.replace("60:61", "58:59") if line == "s_or_b64 exec, exec, s[60:61]" else line for line in masked_region()], "Unexpected execution mask restore") must_reject(translate, [line for line in region if line != CMPX_MOV_RESTORE]) - # Out of scope for this stage: e64, SDWA, f16/f64 and class, VSRC1 not a VGPR (a VGPR pair at 64 bits), + # Out of scope for this stage: e64, SDWA, f16/f64 and their class forms, VSRC1 not a VGPR (a pair at 64 bits), # the 16-bit f/t forms gfx10 lacks, a float token on a 16-bit integer, and source modifiers. for compare in ("v_cmpx_gt_f32_e64 s44, v12", "v_cmpx_gt_f32_sdwa s44, v12 src0_sel:DWORD src1_sel:DWORD", "v_cmpx_gt_f16_e32 s44, v12", "v_cmpx_gt_f64_e32 s[44:45], v[12:13]", "v_cmpx_t_i16_e32 s44, v12", "v_cmpx_gt_i16_e32 1.0, v12", "v_cmpx_gt_u64_e32 s[44:45], v12", "v_cmpx_gt_i64_e32 v[12:13], s[44:45]", "v_cmpx_gt_u16_e64 s44, v12", - "v_cmpx_class_f32_e32 s44, v12", "v_cmpx_gt_f32_e32 v12, s44", + "v_cmpx_class_f32_e64 s44, v12", "v_cmpx_class_f32_e32 v12, s44", + "v_cmpx_class_f32_e32 -v13, v12", "v_cmpx_class_f32_e32 |v13|, v12", + "v_cmpx_class_f32_sdwa s44, v12 src0_sel:DWORD src1_sel:DWORD", + "v_cmpx_class_f16_e32 s44, v12", "v_cmpx_class_f64_e32 s[44:45], v12", + "v_cmpx_gt_f32_e32 v12, s44", "v_cmpx_gt_f32_e32 -v13, v12", "v_cmpx_gt_f32_e32 |v13|, v12", "v_cmpx_gt_f32 s44, v12", "v_cmpx_gt_f32_e32 s44"): must_reject(translate, cmpx_region(compare=compare)) @@ -15498,6 +15576,8 @@ def check_binary(directory, assembler, objcopy, library): *(cmpx_predicate_group(kind, first) for kind, first in CMPX_PREDICATE_GROUPS))) fixtures.extend((cmpx64_group(kind, group), translate_int) for kind in ("i64", "u64") for group in (0, 1)) fixtures.append((cmpx_skip_asm(), translate, "gfx1013", "", cmpx_skip())) + fixtures.extend((program, translate) for program in (cmpx_class_region(), cmpx_class_region(CMPX_OR_RESTORE), + cmpx_class_group())) fixtures.extend((program, translate_int) for op in SHIFT64_OPS for program in shift64_programs(op).values()) fixtures.extend((region_body_program(body, approximate), translate) for _, body, _, approximate in REGION_BODY_FORMS) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 80f5dfc1a..72a243015 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -3201,13 +3201,15 @@ def match(pattern): scalar.masked = True scc = None elif m := match(rf"v_cmpx_(?:({'|'.join(COMPARE)})_f32|({'|'.join(INT_COMPARE)})_(i32|u32|i64|u64)" - rf"|(eq|ne|lt|le|gt|ge)_(i16|u16))_e32 ([^,]+), ([^,]+)"): + rf"|(eq|ne|lt|le|gt|ge)_(i16|u16)|(class)_f32)_e32 ([^,]+), ([^,]+)"): # A masked-if opened by a VOPC e32 compare that writes EXEC (issue #932). It must directly # follow `s_mov_b64 s[a:b], exec` of the known entry mask, so EXEC becomes the entry mask # intersected with the comparison, as after s_and_saveexec_b64. v_cmpx writes neither VCC nor # SCC, so both keep their tracked values; the region closes with s_mov_b64 or s_or_b64. # The integer forms compare as the v_cmp of the same width (gfx10 has no f/t forms at 16 bits). - fop, iop, kind, op16, kind16, src0, src1 = m.groups() + # v_cmpx_class_f32 tests the class of the raw binary32 encoding in src0 against the mask in VSRC1, + # as the e32 v_cmp_class_f32 does. + fop, iop, kind, op16, kind16, cls, src0, src1 = m.groups() if op16 is not None: iop, kind = op16, kind16 previous = instructions[i - 1] if i else "" @@ -3223,6 +3225,10 @@ def match(pattern): raise ValueError(f"Invalid VOPC e32 operands: {line}") if fop is not None: expr = f32_comparison(fop, [src0, src1], scalar, vector, pending, sample_dest) + elif cls is not None: + operand = fp_operand(src0, scalar, vector, pending, sample_dest) + bits = fp_operand(src1, scalar, vector, pending, sample_dest) + expr = f"(class32({operand}) & asuint({bits})) != 0u" elif kind in ("i64", "u64"): declarations, expr = int64_comparison(i, iop, kind, [src0, src1], "e32", scalar, vector, pending, sample_dest) From 639ef5a129ae76cb8a5cf1fabf3d79ce0e33460d Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 11:57:05 +0100 Subject: [PATCH 011/775] cpu: require SSE RFBM bit for MXCSR liveness in XRSTOR AOT --- tests/cpu/xsave_state_check.py | 30 ++++++++++++++++++++++++++---- tools/cpu_xsave_aot.py | 5 +++-- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/tests/cpu/xsave_state_check.py b/tests/cpu/xsave_state_check.py index 8bd7e4262..e2ade2deb 100644 --- a/tests/cpu/xsave_state_check.py +++ b/tests/cpu/xsave_state_check.py @@ -1913,12 +1913,14 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.R8)), Instruction.create_mem(Code.XSAVE64_MEM, MemoryOperand(R.R8)), ret_ins))) - # MXCSR is defined by a restore selecting SSE or AVX; an x87-only save stores no MXCSR. - alt_accept.append(("xrstor_avx_vzeroupper_xsaveopt64_avx", ( - mov_eax_4, + # MXCSR is defined by a restore selecting SSE (RFBM[1]); an x87-only save stores no MXCSR, and + # compacted XRSTOR with RFBM=4 (AVX only) leaves MXCSR unchanged. + alt_accept.append(("xrstor_sse_vzeroupper_xsaveopt64_avx", ( + mov_eax_2, xor_edx, Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), Instruction.create(Code.VEX_VZEROUPPER), + mov_eax_4, Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins))) alt_accept.append(("xrstor_x87_xsaveopt64_x87", ( @@ -1933,7 +1935,7 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) "xrstor_xsavec64": "op_xsavec(state, r8, rax, rdx, true);", "xsavec_then_xrstor_same_buffer": "op_xrstor(state, r8, rax, rdx, true);", "xrstor_xsaveopt64": "op_xsaveopt(state, r8, rax, rdx, true);", - "xrstor_avx_vzeroupper_xsaveopt64_avx": "op_xsaveopt(state, r8, rax, rdx, true);", + "xrstor_sse_vzeroupper_xsaveopt64_avx": "op_xsaveopt(state, r8, rax, rdx, true);", "xrstor_x87_xsaveopt64_x87": "op_xsaveopt(state, r8, rax, rdx, true);", "vmovdqa_ymm_roundtrip": "load256(rcx, true)", "movdqa_xmm_roundtrip": "store128(r8, get_xmm(state, 3), true);", @@ -1951,6 +1953,17 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) canon_raw = _encode_seq(mov_eax_7, xor_edx, Instruction.create_mem(Code.XSAVE64_MEM, MemoryOperand(R.R8)), ret_ins) canon_src, canon_count = lift_code("canon_bare", 0x1000, canon_raw, entry_state="canonical") assert canon_count == 4 and "Entry-state profile: canonical" in canon_src + for label, seq in ( + ("xrstor_avx_xsaveopt64_avx", ( + mov_eax_4, xor_edx, Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), + Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins)), + ("xrstor_avx_vzeroupper_xsaveopt64_avx", ( + mov_eax_4, xor_edx, Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), + Instruction.create(Code.VEX_VZEROUPPER), + Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins)), + ): + src, count = lift_code(label, 0x1000, _encode_seq(*seq), entry_state="canonical") + assert count == len(seq) and "Entry-state profile: canonical" in src, label # Also verify runtime #GP for bounded mask contract (EDX != 0 / EAX & ~7 != 0) # and acceptance of invalid MXCSR when RFBM == 1 (RFBM & 6 == 0). @@ -1997,6 +2010,15 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) _encode_seq(Instruction.create(Code.VEX_VZEROUPPER), mov_eax_4, xor_edx, Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins), "stores MXCSR before any restore defined it"), + ("xrstor_avx_xsaveopt64_avx_mxcsr_undefined", + _encode_seq(mov_eax_4, xor_edx, Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), + Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins), + "stores MXCSR before any restore defined it"), + ("xrstor_avx_vzeroupper_xsaveopt64_avx_mxcsr_undefined", + _encode_seq(mov_eax_4, xor_edx, Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), + Instruction.create(Code.VEX_VZEROUPPER), + Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins), + "stores MXCSR before any restore defined it"), ("x87_restore_vzeroupper_xsaveopt64_x87_avx_mxcsr_undefined", _encode_seq(mov_eax_1, xor_edx, Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), Instruction.create(Code.VEX_VZEROUPPER), diff --git a/tools/cpu_xsave_aot.py b/tools/cpu_xsave_aot.py index 1936a8721..3c14642c8 100644 --- a/tools/cpu_xsave_aot.py +++ b/tools/cpu_xsave_aot.py @@ -928,8 +928,9 @@ def require_xsave_masks(ins): rdx_val = const_gpr.get("rdx") if rdx_val == 0 and rax_val is not None and (rax_val & ~7) == 0: defined_xcomp |= rax_val & 7 - # xrstor loads MXCSR whenever RFBM selects SSE or AVX. - if rax_val & 6: + # Only RFBM[1] (SSE) guarantees MXCSR is defined across both standard and compacted XRSTOR; + # compacted format with RFBM=4 (AVX only) leaves MXCSR unchanged. + if rax_val & 2: defined_mxcsr = True defined_xmm.update(range(6)) defined_ymm.update(range(6)) From 73e2110f41211d6a9c1950d3c221f9dcb2165989 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:01:44 +0100 Subject: [PATCH 012/775] cpu: add non-default entry-MXCSR control for AVX-only compacted XRSTOR --- CMakeLists.txt | 3 +- tests/cpu/xsave_state.asm | 24 ++++++++++++++ tests/cpu/xsave_state.def | 2 ++ tests/cpu/xsave_state_check.py | 57 +++++++++++++++++++++++++++++++--- 4 files changed, 80 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 066a925a7..6c90952ee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2264,6 +2264,7 @@ if(EXISTS "${INTAKE_PYTHON}") "op_xrstor64_xsavec64_sse,op_xrstor64_xsavec64_x87_avx,op_xsavec64_dynmask," "op_xrstor64_xsaveopt,op_xrstor64_xsaveopt64,op_xrstor64_xsaveopt64_sse," "op_xrstor64_xsaveopt64_x87_avx,op_xrstor64_xsaveopt64_avx,op_xsaveopt64_dynmask," + "op_xrstor64_sse_compacted_avx_xsaveopt64_avx," "op_xsavec_xrstor_all,op_xsavec_xrstor_x87_avx,op_xsavec_xrstor_x87_sse," "op_xsavec_xrstor_avx_only,op_xsavec_xrstor_sse_only,op_xrstor64_compacted_dynmask") string(CONCAT cpu_xsave_state_original_exports ${cpu_xsave_state_original_exports}) @@ -2281,7 +2282,7 @@ if(EXISTS "${INTAKE_PYTHON}") set(cpu_xsave_state_canonical_cpp "${CMAKE_CURRENT_BINARY_DIR}/cpu_xsave_state_canonical_lifted.cpp") add_custom_command(OUTPUT "${cpu_xsave_state_canonical_cpp}" COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/cpu_xsave_aot.py" - "$" "op_xsave_only,op_xsave64_only" + "$" "op_xsave_only,op_xsave64_only,op_xrstor64_avx_xsaveopt64_avx" "${cpu_xsave_state_canonical_cpp}" --entry-state canonical DEPENDS cpu_xsave_state_original tools/cpu_xsave_aot.py tools/cpu_leaf_aot.py VERBATIM) add_library(cpu_xsave_state_canonical_lifted SHARED "${cpu_xsave_state_canonical_cpp}") diff --git a/tests/cpu/xsave_state.asm b/tests/cpu/xsave_state.asm index e729ca0b0..d6b7cc759 100644 --- a/tests/cpu/xsave_state.asm +++ b/tests/cpu/xsave_state.asm @@ -234,6 +234,30 @@ op_xrstor64_xsaveopt64_avx PROC FRAME ret op_xrstor64_xsaveopt64_avx ENDP +; RFBM = AVX alone from [rcx]: standard format defines MXCSR, compacted format leaves caller MXCSR untouched; +; requires --entry-state canonical so the compacted path cannot observe entry MXCSR under the default profile. +op_xrstor64_avx_xsaveopt64_avx PROC FRAME + .endprolog + mov eax, 4 + xor edx, edx + xrstor64 [rcx] + xsaveopt64 [r8] + ret +op_xrstor64_avx_xsaveopt64_avx ENDP + +; SSE restore defines MXCSR before an AVX-only (compacted or standard) restore and XSAVEOPT64(4). +op_xrstor64_sse_compacted_avx_xsaveopt64_avx PROC FRAME + .endprolog + mov r10, rdx + mov eax, 2 + xor edx, edx + xrstor64 [rcx] + mov eax, 4 + xrstor64 [r10] + xsaveopt64 [r8] + ret +op_xrstor64_sse_compacted_avx_xsaveopt64_avx ENDP + ; The request mask comes from input_b (RAX = [rdx], RDX = [rdx+8]). op_xsaveopt64_dynmask PROC FRAME .endprolog diff --git a/tests/cpu/xsave_state.def b/tests/cpu/xsave_state.def index 099ba93cd..83c7ba0ff 100644 --- a/tests/cpu/xsave_state.def +++ b/tests/cpu/xsave_state.def @@ -21,6 +21,8 @@ EXPORTS op_xrstor64_xsaveopt64_sse op_xrstor64_xsaveopt64_x87_avx op_xrstor64_xsaveopt64_avx + op_xrstor64_avx_xsaveopt64_avx + op_xrstor64_sse_compacted_avx_xsaveopt64_avx op_xsaveopt64_dynmask op_xsavec_xrstor_all op_xsavec_xrstor_x87_avx diff --git a/tests/cpu/xsave_state_check.py b/tests/cpu/xsave_state_check.py index e2ade2deb..23940af51 100644 --- a/tests/cpu/xsave_state_check.py +++ b/tests/cpu/xsave_state_check.py @@ -21,11 +21,15 @@ DEFAULT_MXCSR = 0x1F80 FILL = b"\x5A" * BUF_LEN -CANONICAL_EXPORTS = ( +ENTRY_ONLY_CANONICAL_EXPORTS = ( "op_xsave_only", "op_xsave64_only", ) +CANONICAL_EXPORTS = ENTRY_ONLY_CANONICAL_EXPORTS + ( + "op_xrstor64_avx_xsaveopt64_avx", +) + XSAVEC_EXPORTS = ( "op_xrstor64_xsavec", "op_xrstor64_xsavec64", @@ -39,6 +43,7 @@ "op_xrstor64_xsaveopt64_sse", "op_xrstor64_xsaveopt64_x87_avx", "op_xrstor64_xsaveopt64_avx", + "op_xrstor64_sse_compacted_avx_xsaveopt64_avx", ) XSAVEOPT_DYNMASK_EXPORT = "op_xsaveopt64_dynmask" @@ -103,6 +108,8 @@ "op_xrstor64_xsaveopt64_sse": (True, True, 2, 0), "op_xrstor64_xsaveopt64_x87_avx": (True, True, 5, 0), "op_xrstor64_xsaveopt64_avx": (True, True, 4, 0), + "op_xrstor64_avx_xsaveopt64_avx": (True, True, 4, 0), + "op_xrstor64_sse_compacted_avx_xsaveopt64_avx": (True, True, 4, 0), } @@ -554,6 +561,13 @@ def reference( m.xsave(out, 0, rfbm=7, is64=True) else: m.xsavec(out, 0, rfbm=7 if altered else rfbm, is64=name != "op_xrstor64_xsavec") + elif name == "op_xrstor64_avx_xsaveopt64_avx": + m.xrstor(a, rfbm=4, is64=True) + m.xsaveopt(out, 0, rfbm=4, is64=True) + elif name == "op_xrstor64_sse_compacted_avx_xsaveopt64_avx": + m.xrstor(a, rfbm=2, is64=True) + m.xrstor(b, rfbm=4, is64=True) + m.xsaveopt(out, 0, rfbm=4, is64=True) elif name in XSAVEOPT_EXPORTS: m.xrstor(a, rfbm=7, is64=True) rfbm = {"op_xrstor64_xsaveopt64_sse": 2, "op_xrstor64_xsaveopt64_x87_avx": 5, "op_xrstor64_xsaveopt64_avx": 4}.get(name, 7) @@ -811,7 +825,7 @@ def assert_equal_output(label: str, name: str, idx, got: bytes, want: bytes) -> and got == bytes(loose) ): return - elif label == "native" and name in XSAVEOPT_EXPORTS: + elif label == "native" and (name in XSAVEOPT_EXPORTS or name == "op_xrstor64_avx_xsaveopt64_avx"): if native_xsaveopt_matches(got, want, EXPORT_MODES[name][2]): return elif label == "native": @@ -842,7 +856,7 @@ def native_exports_for_host(native: dict, has_xsavec: bool, has_xsaveopt: bool = name: fn for name, fn in native.items() if (has_xsavec or (name not in XSAVEC_EXPORTS and name not in COMPACTED_EXPORTS)) - and (has_xsaveopt or name not in XSAVEOPT_EXPORTS) + and (has_xsaveopt or (name not in XSAVEOPT_EXPORTS and name != "op_xrstor64_avx_xsaveopt64_avx")) } @@ -866,7 +880,7 @@ def check_fault_controls( misalign_checks = 0 for off in (16, 8): - for name in CANONICAL_EXPORTS: + for name in ENTRY_ONLY_CANONICAL_EXPORTS: for label, is_native, fn in (("native", True, native_fns[name]), ("canonical-lifted", False, canonical_fns[name])): buf_a, ptr_a, _, _, _ = alloc_aligned_buffer(valid_a) buf_out, ptr_out, pre, p_off, post = alloc_aligned_buffer(FILL, offset=off) @@ -1124,7 +1138,7 @@ def check_entry_state_contracts( struct.pack_into(" XSAVEOPT64(4): + # compacted XRSTOR(4) leaves MXCSR untouched, so native retains caller's 0x3F80 while + # canonical-lifted supplies 0x1F80; standard-format XRSTOR(4) and SSE-defined XRSTOR(2)->XRSTOR(4) + # controls still load 0x5F80 from the image and never observe caller MXCSR. + compacted_avx = compacted_image(mxcsr_mask, 4, COMPACTED_BIT | 4, 4, mxcsr=0x5F80 & mxcsr_mask, seed=303) + standard_avx = make_xsave_image(mxcsr_mask, xstate_bv=4, mxcsr=0x5F80 & mxcsr_mask, seed=304) + got_l_comp = invoke_lifted(canonical_fns["op_xrstor64_avx_xsaveopt64_avx"], compacted_avx, dummy) + assert struct.unpack_from(" Date: Tue, 24 Nov 2026 12:02:33 +0100 Subject: [PATCH 013/775] tests: bind SSE compacted MXCSR control outside single-input xsave_pairs loop --- tests/cpu/xsave_state_check.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/tests/cpu/xsave_state_check.py b/tests/cpu/xsave_state_check.py index 23940af51..2fa6916ca 100644 --- a/tests/cpu/xsave_state_check.py +++ b/tests/cpu/xsave_state_check.py @@ -43,8 +43,8 @@ "op_xrstor64_xsaveopt64_sse", "op_xrstor64_xsaveopt64_x87_avx", "op_xrstor64_xsaveopt64_avx", - "op_xrstor64_sse_compacted_avx_xsaveopt64_avx", ) +SSE_COMPACTED_CONTROL_EXPORT = "op_xrstor64_sse_compacted_avx_xsaveopt64_avx" XSAVEOPT_DYNMASK_EXPORT = "op_xsaveopt64_dynmask" # XSAVEC then XRSTOR of the same buffer: (xsavec RFBM, xrstor RFBM). The save mask leaves a component out of XCOMP_BV @@ -825,7 +825,9 @@ def assert_equal_output(label: str, name: str, idx, got: bytes, want: bytes) -> and got == bytes(loose) ): return - elif label == "native" and (name in XSAVEOPT_EXPORTS or name == "op_xrstor64_avx_xsaveopt64_avx"): + elif label == "native" and ( + name in XSAVEOPT_EXPORTS or name in ("op_xrstor64_avx_xsaveopt64_avx", SSE_COMPACTED_CONTROL_EXPORT) + ): if native_xsaveopt_matches(got, want, EXPORT_MODES[name][2]): return elif label == "native": @@ -856,7 +858,10 @@ def native_exports_for_host(native: dict, has_xsavec: bool, has_xsaveopt: bool = name: fn for name, fn in native.items() if (has_xsavec or (name not in XSAVEC_EXPORTS and name not in COMPACTED_EXPORTS)) - and (has_xsaveopt or (name not in XSAVEOPT_EXPORTS and name != "op_xrstor64_avx_xsaveopt64_avx")) + and ( + has_xsaveopt + or (name not in XSAVEOPT_EXPORTS and name not in ("op_xrstor64_avx_xsaveopt64_avx", SSE_COMPACTED_CONTROL_EXPORT)) + ) } @@ -1713,7 +1718,9 @@ def check_differential( native_altered_path: Path, ) -> None: lifted_lib, lifted = bind_exports( - lifted_path, "lifted_", DEFINED_EXPORTS + (DYNMASK_EXPORT, XSAVEOPT_DYNMASK_EXPORT) + COMPACTED_EXPORTS + lifted_path, + "lifted_", + DEFINED_EXPORTS + (DYNMASK_EXPORT, XSAVEOPT_DYNMASK_EXPORT, SSE_COMPACTED_CONTROL_EXPORT) + COMPACTED_EXPORTS, ) lifted_lib.host_has_xsave.argtypes = [] lifted_lib.host_has_xsave.restype = ctypes.c_uint32 @@ -1748,7 +1755,7 @@ def check_differential( fp_cpuid = int(lifted_lib.host_fp_err_cpuid_info()) mxcsr_mask = int(lifted_lib.host_mxcsr_mask()) - _, native = bind_exports(native_path, "", EXPORTS + COMPACTED_EXPORTS) + _, native = bind_exports(native_path, "", EXPORTS + COMPACTED_EXPORTS + (SSE_COMPACTED_CONTROL_EXPORT,)) native = native_exports_for_host(native, has_xsavec, has_xsaveopt) _, native_altered = bind_exports(native_altered_path, "", ALTERED_CANONICAL_EXPORTS) altered_lib, altered = bind_exports(altered_path, "lifted_", ALTERED_DEFINED_EXPORTS + ALTERED_COMPACTED_EXPORTS) From bb3d5bd47c8e5da31aaeb545d29fe3a9f051148f Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:03:18 +0100 Subject: [PATCH 014/775] tests: include new xsaveopt controls in host gating check --- tests/cpu/xsave_state_check.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/cpu/xsave_state_check.py b/tests/cpu/xsave_state_check.py index 2fa6916ca..60d15b78c 100644 --- a/tests/cpu/xsave_state_check.py +++ b/tests/cpu/xsave_state_check.py @@ -1881,7 +1881,12 @@ def check_differential( # A host without XSAVEC must not be handed native xsavec fixtures. gated = native_exports_for_host(native, False, False) - unsupported = set(XSAVEC_EXPORTS) | set(XSAVEOPT_EXPORTS) | set(COMPACTED_EXPORTS) + unsupported = ( + set(XSAVEC_EXPORTS) + | set(XSAVEOPT_EXPORTS) + | set(COMPACTED_EXPORTS) + | {"op_xrstor64_avx_xsaveopt64_avx", SSE_COMPACTED_CONTROL_EXPORT} + ) assert not unsupported & set(gated) and set(native) - unsupported == set(gated) check_fault_controls(harness, gated, lifted, canonical, mxcsr_mask) From c6571ee981ab37cb98e713b69de2f9a750f9980b Mon Sep 17 00:00:00 2001 From: legacy-code-archaeologist <359844974+legacy-code-archaeologist@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:08:34 +0100 Subject: [PATCH 015/775] cpu: accept FFREE of a statically empty register in the x87 profile FFREE ST(i) is accepted when ST(i) is known to be empty at translation time (i at least the depth). It changes neither occupancy nor TOP, and C0 to C3 become undefined. FFREE of an occupied register stays outside the profile: freeing the deepest one keeps TOP while the stack shrinks, and freeing another leaves a hole. cpu_aot_x87_examine gains ffree_empty: FFREE of empty registers at depths 0, 1 and 7, a final legal push from depth 7, TOP after each group (FNSTSW AX, AH masked to TOP) and the stored values. Two controls must mismatch (FFREE that frees ST(0) instead, and a TOP moved as by a pop), and a reader of C0 after FFREE must be refused. The rejection cases "ffree st(1)" at depth 1 in x87_add.py and x87_moves.py freed an empty register and are accepted now; they use the occupied ffree st(0) instead and still expect a refusal. Windows 11 26100, ctest --preset dev --no-tests=error -R '^cpu_aot_x87_examine$' -V: 884 cases over 7 exports matched in the native and translated DLLs (TOP 0, 7, 0); controls ffree/freetop 34/68 mismatches; 15 sequences rejected. Release preset passes the same. Refs #1338 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 4 ++-- docs/experiments.md | 4 +++- tests/cpu/x87_add.py | 2 +- tests/cpu/x87_examine.asm | 43 ++++++++++++++++++++++++++++++++++++++- tests/cpu/x87_examine.def | 1 + tests/cpu/x87_examine.py | 27 +++++++++++++++++------- tests/cpu/x87_moves.py | 2 +- tools/x87_lower.py | 14 ++++++++++--- 8 files changed, 81 insertions(+), 16 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0acbae4b7..2258e1058 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4007,9 +4007,9 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$" "$" ${x87_fnstcw_control_files}) cpu_asm_fixture(cpu_x87_examine x87_examine) - # The lifted DLL and six mutated controls that the check requires to mismatch. + # The lifted DLL and eight mutated controls that the check requires to mismatch. set(x87_examine_control_files "") - foreach(variant IN ITEMS lifted normal unsigned positive legacy ffreep fftop) + foreach(variant IN ITEMS lifted normal unsigned positive legacy ffreep fftop ffree freetop) set(x87_examine_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_x87_examine_${variant}.cpp") add_custom_command(OUTPUT "${x87_examine_fixture}" COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_examine.py" diff --git a/docs/experiments.md b/docs/experiments.md index 2712f4d85..276996329 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1517,7 +1517,9 @@ Seven native-only exports move on the caller's flags. `fcmovb` and `fcmove` move The profile also accepts the 8087/287 controls `fneni`, `fndisi` and `fnsetpm`, which the 80387 and later execute as `fnop`; `feni` and `fdisi` decode as `wait` and the no-wait form, and ML64 assembles `fsetpm` as `fnsetpm` without a `wait` and has no `fnsetpm` spelling. A fifth export, `legacy_controls`, runs `feni`, `fneni`, `fdisi`, `fndisi` and `fsetpm` between a load and a store, so the check now has 5 exports and 816 cases. On Windows 10 build 19045 the native run stored the loaded value unchanged and returned with control word 0x027F and an empty stack in every case, as the translation does. A fourth control, which flips the sign of ST(0) at `fnsetpm`, gave 34 mismatches, one per `legacy_controls` case, and translation rejects a reader of C0 after `fneni` or `fnsetpm`. -The profile also accepts `ffreep st(0)` on a nonempty stack: it tags ST(0) empty and pops it, like `fstp st(0)` without a store, so TOP moves up by one. On an empty stack it is rejected. `ffree`, `ffreep` with another register, `fincstp` and `fdecstp` stay outside the profile: they would free a register below ST(0), or move TOP without changing occupancy, and the profile derives TOP from a contiguous depth. Like every other x87 instruction, `ffreep` leaves C0 to C3 undefined. A sixth export, `ffreep_top`, pushes the input, 1.0 and 0.0, and then runs `ffreep st(0)` at depths 3, 2 and 1. It records TOP after each `fnstsw ax` (AH masked to TOP) and stores the values left below. The check now has 6 exports and 850 cases. On Windows 11 build 26100 the native run gave TOP 5, 6, 7 and 0 and the values unchanged, as the translation does. Two more controls must mismatch: one where `ffreep` also overwrites the deepest register with the one above it, which gave 33 mismatches (the input 1.0 hides it), and one where TOP stays 5 after the first `ffreep`, which gave 34. Translation rejects `ffreep` on an empty stack, a reader of C0 or C1 after `ffreep`, `ffreep st(2)`, `ffree st(0)`, `ffree st(1)`, `fincstp` and `fdecstp`. +The profile also accepts `ffreep st(0)` on a nonempty stack: it tags ST(0) empty and pops it, like `fstp st(0)` without a store, so TOP moves up by one. On an empty stack it is rejected. `ffree` of an occupied register, `ffreep` with another register, `fincstp` and `fdecstp` stay outside the profile: they would free a register below ST(0), or move TOP without changing occupancy, and the profile derives TOP from a contiguous depth. Like every other x87 instruction, `ffreep` leaves C0 to C3 undefined. A sixth export, `ffreep_top`, pushes the input, 1.0 and 0.0, and then runs `ffreep st(0)` at depths 3, 2 and 1. It records TOP after each `fnstsw ax` (AH masked to TOP) and stores the values left below. The check now has 6 exports and 850 cases. On Windows 11 build 26100 the native run gave TOP 5, 6, 7 and 0 and the values unchanged, as the translation does. Two more controls must mismatch: one where `ffreep` also overwrites the deepest register with the one above it, which gave 33 mismatches (the input 1.0 hides it), and one where TOP stays 5 after the first `ffreep`, which gave 34. Translation rejects `ffreep` on an empty stack, a reader of C0 or C1 after `ffreep`, `ffreep st(2)`, `ffree st(0)`, `ffree st(1)`, `fincstp` and `fdecstp`. + +`ffree st(i)` is accepted when ST(i) is known to be empty at translation time, that is when `i` is at least the depth. It then changes neither occupancy nor TOP, and C0 to C3 become undefined. `ffree` of an occupied register stays outside the profile: freeing the deepest one would keep TOP while the stack shrinks, and freeing another would leave a hole. A seventh export, `ffree_empty`, runs `ffree st(0)` and `ffree st(7)` at depth 0, `ffree st(1)`, `st(4)` and `st(7)` at depth 1, and `ffree st(7)` at depth 7 followed by one more push. It records TOP after each group, and from depth 8 stores the pushed 0.0, the 1.0 below it and the input at the bottom. The check now has 7 exports and 884 cases. On Windows 11 build 26100 the native run gave TOP 0, 7 and 0, the final push did not overflow, and every stored value matched, as in the translation. Two more controls must mismatch. One frees ST(0) instead of ST(7) at depth 7, which gave 34 mismatches. The other moves TOP as a pop does, so the status word at depth 1 reads TOP 0; it gave 68 mismatches, because `ffreep_top` also reads TOP 7 at depth 1. Translation rejects a reader of C0 after `ffree` of an empty register, and `ffree st(0)` and `ffree st(1)` of occupied registers. The rejection cases `ffree st(1)` at depth 1 in `cpu_aot_x87_add` and `cpu_aot_x87_moves` freed an empty register, so they now use `ffree st(0)`. `lower(..., x87=x87_lower.Checked(reject))` is the checked entry of the profile. It also accepts `fldcw m16`, and keeps the control word in a local of the lowered function, `fninit` and `finit`, which load `0x037F`, clear C0 to C3 and empty every register, `fbld` (`cpu_aot_x87_bcd`), and `fprem` and `fprem1` (`cpu_aot_x87_fprem`). The arithmetic, `fsqrt`, `fscale`, `frndint`, `fist` and `fistp`, the m32 and m64 stores, `fnstcw` and the five inexact constant loads all follow that word. The precision control applies only to the arithmetic and `fsqrt`. `fldcw` accepts a word with all six exceptions masked and precision control 00, 10 or 11 (24, 53 or 64 bits). It keeps the word as `fnstcw` reads it back: bit 6 reads as 1, bits 7 and 13 to 15 as 0, and bit 12 is kept. The lowered function leaves through the caller's `reject` statement with a status in these cases: diff --git a/tests/cpu/x87_add.py b/tests/cpu/x87_add.py index e829d3663..b6bb1cb4d 100644 --- a/tests/cpu/x87_add.py +++ b/tests/cpu/x87_add.py @@ -488,7 +488,7 @@ def attempt(hex_bytes, *, x87=True, calls=None, exits=None): "fnstsw m16": (attempt(f"{fld} dd 3a {fstp} c3"), "stores status-word bits"), "fldcw": (attempt(f"d9 29 {fld} {fstp} c3"), "fldcw"), "fninit": (attempt(f"{fld} db e3 {fstp} c3"), "unsupported x87 operation"), - "ffree st(1)": (attempt(f"{fld} dd c1 {fstp} c3"), "unsupported x87 operation"), + "ffree st(0)": (attempt(f"{fld} dd c0 {fstp} c3"), "frees an occupied register"), "a ninth push": (attempt(f"{fld} " * 9 + f"{fstp} " * 9 + "c3"), "x87 stack overflow"), "fstp on an empty stack": (attempt(f"{fstp} c3"), "x87 stack underflow"), "faddp with one value": (attempt(f"{fld} de c1 {fstp} c3"), "x87 stack underflow"), diff --git a/tests/cpu/x87_examine.asm b/tests/cpu/x87_examine.asm index 8d766618d..9de01d2e0 100644 --- a/tests/cpu/x87_examine.asm +++ b/tests/cpu/x87_examine.asm @@ -1,7 +1,7 @@ ; coverage: source cpu_aot_x87_examine ; Source-owned differential fixture for FTST, FXAM, FICOM, FICOMP, FNOP, FNCLEX and FCLEX, and the ; 8087/287 controls FENI, FNENI, FDISI, FNDISI and FSETPM (ML64 has no FNSETPM spelling and assembles -; FSETPM without a WAIT), and FFREEP ST(0), in the x87 leaf-function profile. Each export reads an input block at RCX (an m80 value at +0, an m16 integer at +; FSETPM without a WAIT), FFREEP ST(0) and FFREE of an empty register, in the x87 leaf-function profile. Each export reads an input block at RCX (an m80 value at +0, an m16 integer at ; +16 and an m32 integer at +24), records C0, C2 and C3 after each status-word writer as bytes of the ; output block at RDX, and returns with the x87 stack empty. .code @@ -204,4 +204,45 @@ ffreep_top PROC FRAME ret ffreep_top ENDP +; FFREE of an already empty register changes neither occupancy nor TOP. Output: TOP bytes (TOP << 3) at +0 +; (depth 0, after ffree st(0) and st(7)), +1 (depth 1, after ffree st(1), st(4) and st(7)) and +2 (depth 8, +; after ffree st(7) at depth 7 and one more load, which must not overflow), then 0.0 at +16, 1.0 at +26 and the +; input m80 at +40. +ffree_empty PROC FRAME + .endprolog + ffree st(0) + ffree st(7) + fnstsw ax + and ah, 38h + mov byte ptr [rdx+0], ah + fld tbyte ptr [rcx] + ffree st(1) + ffree st(4) + ffree st(7) + fnstsw ax + and ah, 38h + mov byte ptr [rdx+1], ah + fld1 + fld1 + fld1 + fld1 + fld1 + fld1 + ffree st(7) + fldz + fnstsw ax + and ah, 38h + mov byte ptr [rdx+2], ah + fstp tbyte ptr [rdx+16] + fstp tbyte ptr [rdx+26] + fstp st(0) + fstp st(0) + fstp st(0) + fstp st(0) + fstp st(0) + fstp tbyte ptr [rdx+40] + mov eax, 0 + ret +ffree_empty ENDP + END diff --git a/tests/cpu/x87_examine.def b/tests/cpu/x87_examine.def index 6060bfc93..d677cc863 100644 --- a/tests/cpu/x87_examine.def +++ b/tests/cpu/x87_examine.def @@ -5,3 +5,4 @@ EXPORTS fnop_fclex legacy_controls ffreep_top + ffree_empty diff --git a/tests/cpu/x87_examine.py b/tests/cpu/x87_examine.py index f1a45448a..a2b6032c9 100644 --- a/tests/cpu/x87_examine.py +++ b/tests/cpu/x87_examine.py @@ -1,11 +1,12 @@ """Compare native and translated FTST, FXAM, FICOM, FICOMP, FNOP, FNCLEX, FCLEX and the 8087/287 controls -FENI, FNENI, FDISI, FNDISI and FSETPM, and FFREEP ST(0), in the x87 profile. +FENI, FNENI, FDISI, FNDISI and FSETPM, FFREEP ST(0) and FFREE of an empty register, in the x87 profile. Each export runs through the native harness (control word 0x027F, empty stack) and writes C0, C2 and C3 after each status-word writer, and any stored m80 value, to its output block. An independent model gives the expected block: comparisons use exact rationals, and FXAM classifies the 80-bit encoding (unsupported, NaN, normal, infinity, zero, empty, denormal); FFREEP ST(0) gives the physical TOP after each pop and leaves the -values below it unchanged. Six mutated translations must each mismatch, and +values below it unchanged, and FFREE of an empty register keeps TOP and every value. Eight mutated translations +must each mismatch, and translation must reject the sequences in check_rejections. """ from fractions import Fraction @@ -17,7 +18,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) import x87_add as base # noqa: E402 (tests/cpu is the script directory) -EXPORTS = ("ftst_fxam", "ficom_m16", "ficom_m32", "fnop_fclex", "legacy_controls", "ffreep_top") +EXPORTS = ("ftst_fxam", "ficom_m16", "ficom_m32", "fnop_fclex", "legacy_controls", "ffreep_top", "ffree_empty") INPUT, OUTPUT = base.INPUT, base.OUTPUT J = 1 << 63 # Mutations of the lifted source that the check requires to mismatch: (pattern, replacement). @@ -32,6 +33,11 @@ "ffreep": (re.compile(re.escape("; // ffreep st(0)")), "x87_slot[0] = x87_slot[1]; // ffreep st(0)"), # A TOP that FFREEP did not move: the status word after the first FFREEP keeps TOP 5. "fftop": (re.compile(re.escape("x87_sw | 0x3000); // fnstsw ax, top 6")), "x87_sw | 0x2800); // fnstsw ax, top 6"), + # FFREE ST(7) that freed ST(0) instead: at depth 7 the 1.0 in ST(0) (slot 6) becomes zero. + "ffree": (re.compile(re.escape("; // ffree st(7)")), "x87_slot[6] = X87Value{0, 0}; // ffree st(7)"), + # FFREE that moved TOP as a pop does: at depth 1 the status word reads TOP 0 instead of 7. The literal also + # matches the depth-1 status read of ffreep_top, so both exports mismatch. + "freetop": (re.compile(re.escape("x87_sw | 0x3800); // fnstsw ax, top 7")), "x87_sw | 0x0000); // fnstsw ax, top 7"), } @@ -110,6 +116,11 @@ def reference(name, data): out[0:4] = bytes((5 << 3, 6 << 3, 7 << 3, 0)) out[16:26] = struct.pack(" 0, FINCSTP and FDECSTP.""" + FNSETPM, FFREEP or FFREE, and FFREE of an occupied register, FFREEP ST(i) for i > 0, FINCSTP and FDECSTP.""" from iced_x86 import Decoder from ffx_version_query import lower @@ -169,8 +180,10 @@ def sequence(op): # fld1; fld1; ffreep st(0); fnstsw ax; test ah, 2 (C1); jne +0; fstp st(0); mov eax, 0; ret "ffreep then a reader of C1": ("d9e8d9e8dfc0dfe0f6c4027500ddd8b800000000c3", "not known"), "ffreep st(2)": ("d9e8d9e8d9e8dfc2ddd8ddd8c3", "unsupported x87 operand"), - "ffree st(0)": ("d9e8ddc0ddd8c3", "unsupported x87 operation"), - "ffree st(1)": ("d9e8d9e8ddc1ddd8ddd8c3", "unsupported x87 operation"), + "ffree st(0)": ("d9e8ddc0ddd8c3", "frees an occupied register"), + # fld1; ftst (C0 known, see the accepted case); ffree st(1) (empty); then the reader of C0 of sequence() + "ffree of an empty register then a reader of C0": (sequence("d9e4ddc1"), "not known"), + "ffree st(1)": ("d9e8d9e8ddc1ddd8ddd8c3", "frees an occupied register"), "fincstp": ("d9e8d9f7ddd8c3", "unsupported x87 operation"), "fdecstp": ("d9e8d9f6ddd8c3", "unsupported x87 operation"), } diff --git a/tests/cpu/x87_moves.py b/tests/cpu/x87_moves.py index 92abe094d..47640d3f6 100644 --- a/tests/cpu/x87_moves.py +++ b/tests/cpu/x87_moves.py @@ -310,7 +310,7 @@ def attempt(hex_bytes): "fxch st(1) as DF C9": (attempt(f"{fld} {fld} df c9 {fstp} {fstp} c3"), "unsupported x87 encoding"), "fnstenv m28": (attempt(f"{fld} d9 32 {fstp} c3"), "unsupported x87 operation"), "fsin": (attempt(f"{fld} d9 fe {fstp} c3"), "unsupported x87 operation"), - "ffree st(1)": (attempt(f"{fld} dd c1 {fstp} c3"), "unsupported x87 operation"), + "ffree st(0)": (attempt(f"{fld} dd c0 {fstp} c3"), "frees an occupied register"), "fdecstp": (attempt(f"{fld} d9 f6 {fstp} c3"), "unsupported x87 operation"), } for case, (message, needle) in rejected.items(): diff --git a/tools/x87_lower.py b/tools/x87_lower.py index 31cf64ed7..eefd3a18d 100644 --- a/tools/x87_lower.py +++ b/tools/x87_lower.py @@ -24,8 +24,10 @@ - FNOP and FNCLEX, which change nothing the profile models (FCLEX decodes as WAIT and FNCLEX), and the 8087/287 controls FNENI, FNDISI and FNSETPM, which later processors execute as FNOP (FENI and FDISI decode as WAIT and FNENI or FNDISI); -- FFREEP ST(0) on a nonempty stack, which tags ST(0) empty and pops it as FSTP ST(0) does without storing it - (FFREE, FFREEP with another register, FINCSTP and FDECSTP stay outside the profile); +- FFREEP ST(0) on a nonempty stack, which tags ST(0) empty and pops it as FSTP ST(0) does without storing it, + and FFREE ST(i) of a register that is already empty (i at least the depth), which changes neither occupancy + nor TOP (FFREE of an occupied register, FFREEP with another register, FINCSTP and FDECSTP stay outside the + profile); A function starts with control word 0x027F, TOP 0, eight empty registers and a clear status word, and must return with the stack empty. The stack depth before every instruction is fixed at translation time, so each register maps to a C++ slot and no TOP is needed at run time. Translation rejects any x87 @@ -116,7 +118,7 @@ M.FCOMIP, M.FUCOMI, M.FUCOMIP, M.FADD, M.FADDP, M.FSUB, M.FSUBP, M.FSUBR, M.FSUBRP, M.FMUL, M.FMULP, M.FDIV, M.FDIVP, M.FDIVR, M.FDIVRP, *IARITHMETIC, M.FNSTCW, M.WAIT, M.FLDCW, M.FCOM, M.FCOMP, M.FCOMPP, M.FUCOM, M.FUCOMP, M.FUCOMPP, M.FNSTSW, M.FTST, M.FICOM, M.FICOMP, - M.FXAM, M.FNOP, M.FNCLEX, M.FPREM, M.FPREM1, M.FNINIT, M.FBLD, M.FBSTP, *LEGACY_CONTROLS, M.FFREEP}) + M.FXAM, M.FNOP, M.FNCLEX, M.FPREM, M.FPREM1, M.FNINIT, M.FBLD, M.FBSTP, *LEGACY_CONTROLS, M.FFREEP, M.FFREE}) # Comparisons into C0, C2 and C3 of the status word; FCOMPP and FUCOMPP pop twice, the other P forms once. STATUS_COMPARES = frozenset({M.FCOM, M.FCOMP, M.FCOMPP, M.FUCOM, M.FUCOMP, M.FUCOMPP}) STATUS_POPS = {M.FCOM: 0, M.FCOMP: 1, M.FCOMPP: 2, M.FUCOM: 0, M.FUCOMP: 1, M.FUCOMPP: 2} @@ -239,6 +241,10 @@ def _effect(i, depth, checked=None): if depth == 0: raise ValueError(f"x87 stack underflow at {i.ip:#x}: {i}") return depth - 1 + if op == M.FFREE: # an occupied register would leave a hole, or keep TOP while the stack shrinks + if i.op0_register - R.ST0 < depth: + raise ValueError(f"unsupported x87 operand at {i.ip:#x}: {i} frees an occupied register") + return depth if op == M.FTST: if depth == 0: raise ValueError(f"x87 stack underflow at {i.ip:#x}: {i}") @@ -663,6 +669,8 @@ def _statement(i, depth, address, checked, parity, status_word=False): return f"; // {LEGACY_CONTROLS[op]}" if op == M.FFREEP: # the pop is the depth change; the freed slot is dead from here on return "; // ffreep st(0)" + if op == M.FFREE: # the register is already empty + return f"; // ffree st({i.op0_register - R.ST0})" if op == M.FTST: # ST(0) compared with +0.0 return f"{{ const int r = x87_compare(x87_slot[{top}], X87Value{{0, 0}}); {COMPARE_SW} }} // ftst" if op in ICOMPARES: From b70aa2ed0fa1ad63d29f0d7f8515aeb384f88ebd Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:09:42 +0100 Subject: [PATCH 016/775] gpu: log the exact fields of a refused slot 70 memory SRV call A refused address SRV call returned with one fixed line. It now names the first refusing check and prints the resource, view, destination and address fields the checks read, for the first eight refusals. Behavior and return paths are unchanged. --- CMakeLists.txt | 5 ++ docs/experiments.md | 27 +++++++ src/startup_stubs/d3d12_memory_srv.inl | 35 ++++++-- src/startup_stubs/d3d12_xs_device.cpp | 1 + src/startup_stubs/memory_srv_report.h | 85 +++++++++++++++++++ tests/startup_address_srv.cpp | 18 ++++- tests/startup_address_srv_check.py | 36 ++++++++- tests/startup_memory_srv_report_check.cpp | 99 +++++++++++++++++++++++ 8 files changed, 299 insertions(+), 7 deletions(-) create mode 100644 src/startup_stubs/memory_srv_report.h create mode 100644 tests/startup_memory_srv_report_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 69d8f0923..932433dc0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -625,6 +625,11 @@ add_executable(startup_packed_target_check tests/startup_packed_target_check.cpp target_include_directories(startup_packed_target_check PRIVATE src) target_compile_features(startup_packed_target_check PRIVATE cxx_std_17) add_test(NAME startup_packed_target COMMAND startup_packed_target_check) +# Diagnostic line for a refused device slot 70 call (src/startup_stubs/memory_srv_report.h). +add_executable(startup_memory_srv_report_check tests/startup_memory_srv_report_check.cpp) +target_include_directories(startup_memory_srv_report_check PRIVATE src) +target_compile_features(startup_memory_srv_report_check PRIVATE cxx_std_17) +add_test(NAME startup_memory_srv_report COMMAND startup_memory_srv_report_check) # Console allocation sizes for depth-with-stencil and multisampled textures # (src/startup_stubs/console_plane_size.h); the mutated run is the negative control. add_executable(startup_plane_size_check tests/startup_plane_size_check.cpp) diff --git a/docs/experiments.md b/docs/experiments.md index 2712f4d85..82584f9dd 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9464,6 +9464,33 @@ cmake --build --preset release --target startup_stream_consumer d3d12_xs_shim ctest --preset release --no-tests=error -R '^startup_address_srv_' -V ``` +### Name the cause of a refused slot 70 call + +A slot 70 call that the runtime refuses leaves the destination descriptor as it was and logs one +line, for the first eight refusals of a process (stderr and `X2W_TRAP_LOG`). The line names the first +check that refused it, in the order the checks run: `null_destination`, `unreadable_resource`, +`unreadable_view`, `null_address`, `unsupported_description`, `destination_outside_view_heaps`, or +`texture_unavailable` (the description passed but no single live texture or published view matches the +address). It then prints what the checks read: resource dimension, format, width by height by depth or +array size, mips, layout, flags, alignment and sample count and quality; view dimension, format and +component mapping, with the mip, plane and array fields for 2D and 2D-array views and the first +element, count, stride and flags for buffer views (any other dimension prints its six raw words); +the destination handle and whether it is a descriptor of a known CBV/SRV/UAV heap; the address and +whether its first byte is readable. Only 2D textures are supported: a buffer view or an +acceleration-structure view is refused with `unsupported_description` and the line says so. No +buffer or acceleration-structure semantics are implemented; what a title expects from such a call +has not been observed in a source-built fixture. + +`startup_memory_srv_report` compares the line field by field for buffer, acceleration-structure +and array views and for unreadable arguments. `startup_address_srv_hardware` and +`startup_address_srv_warp` also match the five lines of their refused calls (zero address, other +width, interior address, a buffer view, a destination off the heap) and show the descriptor unchanged. + +```powershell +cmake --build --preset release --target startup_memory_srv_report_check startup_stream_consumer d3d12_xs_shim +ctest --preset release --no-tests=error -R '^(startup_memory_srv_report|startup_address_srv_)' -V +``` + ### Sample address-only BC3/BC7 textures in translated draws The translated draw path can sample a read-only BC3_UNORM or BC7_UNORM SRV diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index b508cee4e..2e7202598 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -142,20 +142,45 @@ ID3D12Resource* sampled_address_texture(Wrapper* resource) return sampled.desktop.Get(); } +// The first check that refuses a call, in the order the checks run; null when every check passes. +const char* memory_srv_refusal(const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) +{ + if (!destination) return "null_destination"; + if (!x2w_local::readable(resource, sizeof(*resource))) return "unreadable_resource"; + if (!x2w_local::readable(input, sizeof(*input))) return "unreadable_view"; + if (!input->address) return "null_address"; + if (!supports_memory_srv(*resource, input->view)) return "unsupported_description"; + if (!memory_srv_destination(destination)) return "destination_outside_view_heaps"; + return nullptr; +} + +// One line with every field the checks read; the caller rate-limits it. +void log_refused_memory_srv(const char* what, const char* reason, const D3D12_RESOURCE_DESC* resource, + const MemoryShaderResourceView* input, u64 destination) +{ + const bool resource_ok = x2w_local::readable(resource, sizeof(*resource)); + const bool input_ok = x2w_local::readable(input, sizeof(*input)); + const u64 address = input_ok ? input->address : 0; + char line[640]; + x2w_startup::report_refused_memory_srv(line, sizeof(line), what, reason, resource_ok ? resource : nullptr, + input_ok ? &input->view : nullptr, address, address && x2w_local::readable(reinterpret_cast(address), 1), + destination, destination && memory_srv_destination(destination)); + log("%s", line); +} + void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { static LONG refused; - if (!destination || !x2w_local::readable(resource, sizeof(*resource)) || - !x2w_local::readable(input, sizeof(*input)) || !input->address || - !supports_memory_srv(*resource, input->view) || !memory_srv_destination(destination)) { - if (first_calls(refused, 8)) log("x2w-d3d12 Device::slot70 unsupported memory SRV arguments"); + if (const char* reason = memory_srv_refusal(resource, input, destination)) { + if (first_calls(refused, 8)) log_refused_memory_srv("unsupported memory SRV arguments", reason, resource, input, destination); return; } Wrapper* texture = (tiled_bc_srv(*resource) || x2w_startup::bc64::supports(*resource)) ? publish_tiled_texture(self, input->address, *resource) : existing_memory_texture(input->address, *resource); if (!texture) { - if (first_calls(refused, 8)) log("x2w-d3d12 Device::slot70 unavailable texture at the supplied base and layout"); + if (first_calls(refused, 8)) + log_refused_memory_srv("unavailable texture at the supplied base and layout", "texture_unavailable", resource, input, destination); return; } view_slot<18, 2>(self, reinterpret_cast(texture), reinterpret_cast(&input->view), destination, 0); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index f291bd081..e7cb73285 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ #include "startup_stubs/derived_blend.h" #include "startup_stubs/placement_publish.h" #include "startup_stubs/placed_build.h" +#include "startup_stubs/memory_srv_report.h" #include "startup_stubs/slice_footprints.h" diff --git a/src/startup_stubs/memory_srv_report.h b/src/startup_stubs/memory_srv_report.h new file mode 100644 index 000000000..a6f04d97a --- /dev/null +++ b/src/startup_stubs/memory_srv_report.h @@ -0,0 +1,85 @@ +// Experimental (docs/startup-runtime.md): one compact diagnostic line for a refused device slot 70 +// call (a shader resource view whose resource is an address). +// +// The line names the first check that refused the call and the fields the checks read, so a tester +// can paste it into an issue: the resource description, the view description, the destination handle +// and whether it lies in a known CBV/SRV/UAV heap, and the address and whether it is readable. It is +// formatted into a caller-supplied fixed buffer and allocates nothing. A null resource or view pointer +// means the guest memory could not be read; its fields are then shown as "unreadable". +#pragma once + +#include + +#include +#include +#include +#include + +namespace x2w_startup { + +// D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE; named here because older headers lack it. +constexpr int srv_dimension_acceleration_structure = 11; + +inline int report_resource(char* out, std::size_t size, const D3D12_RESOURCE_DESC* r) +{ + if (!r) return std::snprintf(out, size, "unreadable"); + return std::snprintf(out, size, "dim=%d fmt=%u size=%llux%ux%u mips=%u layout=0x%x flags=0x%x align=%llu samples=%u/%u", + static_cast(r->Dimension), static_cast(r->Format), + static_cast(r->Width), static_cast(r->Height), + static_cast(r->DepthOrArraySize), static_cast(r->MipLevels), + static_cast(r->Layout), static_cast(r->Flags), + static_cast(r->Alignment), static_cast(r->SampleDesc.Count), + static_cast(r->SampleDesc.Quality)); +} + +inline int report_view(char* out, std::size_t size, const D3D12_SHADER_RESOURCE_VIEW_DESC* v) +{ + if (!v) return std::snprintf(out, size, "unreadable"); + const int dimension = static_cast(v->ViewDimension); + const int head = std::snprintf(out, size, "dim=%d fmt=%u map=0x%x ", dimension, static_cast(v->Format), + static_cast(v->Shader4ComponentMapping)); + if (head < 0 || static_cast(head) >= size) return head; + char* tail = out + head; + const std::size_t room = size - static_cast(head); + switch (v->ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE2D: + return std::snprintf(tail, room, "mostmip=%u mips=%u plane=%u clamp=%g", v->Texture2D.MostDetailedMip, + v->Texture2D.MipLevels, v->Texture2D.PlaneSlice, + static_cast(v->Texture2D.ResourceMinLODClamp)); + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: + return std::snprintf(tail, room, "mostmip=%u mips=%u first=%u count=%u plane=%u clamp=%g", + v->Texture2DArray.MostDetailedMip, v->Texture2DArray.MipLevels, + v->Texture2DArray.FirstArraySlice, v->Texture2DArray.ArraySize, + v->Texture2DArray.PlaneSlice, static_cast(v->Texture2DArray.ResourceMinLODClamp)); + case D3D12_SRV_DIMENSION_BUFFER: + return std::snprintf(tail, room, "first=%llu count=%u stride=%u flags=0x%x (buffer views are not supported)", + static_cast(v->Buffer.FirstElement), v->Buffer.NumElements, + v->Buffer.StructureByteStride, static_cast(v->Buffer.Flags)); + default: { + // Any other dimension: the six words after the component mapping, as stored. + std::uint32_t words[6]{}; + std::memcpy(words, &v->Buffer, sizeof(words)); + return std::snprintf(tail, room, "raw=%08x,%08x,%08x,%08x,%08x,%08x%s", words[0], words[1], words[2], words[3], + words[4], words[5], + dimension == srv_dimension_acceleration_structure ? " (acceleration structure views are not supported)" : ""); + } + } +} + +// `what` is the fixed phrase of the call site, `reason` the first refusing check. +inline int report_refused_memory_srv(char* out, std::size_t size, const char* what, const char* reason, + const D3D12_RESOURCE_DESC* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* view, + std::uint64_t address, bool address_readable, std::uint64_t destination, + bool destination_in_view_heap) +{ + char resource_text[224]; + char view_text[256]; + report_resource(resource_text, sizeof(resource_text), resource); + report_view(view_text, sizeof(view_text), view); + return std::snprintf(out, size, + "x2w-d3d12 Device::slot70 %s: reason=%s res{%s} view{%s} dest=0x%llx dest_in_view_heap=%d address=0x%llx address_readable=%d", + what, reason, resource_text, view_text, static_cast(destination), destination_in_view_heap ? 1 : 0, + static_cast(address), address_readable ? 1 : 0); +} + +} // namespace x2w_startup diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 67b977f29..cf2f28b6b 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -78,7 +78,23 @@ int draw_address_srvs(ID3D12Device* desktop, void* guest, void* list) auto wrong_desc = desc; wrong_desc.Width = 1; publish(wrong_desc, ptr(planes[0].data())); draw(5); - publish(desc, ptr(planes[0].data()) + 1); draw(6); // Interior address, not the registered base. + publish(desc, ptr(planes[0].data()) + 1); // Interior address, not the registered base. + // Refusals that name their cause in the log; draw 6 shows each left the descriptor alone. + D3D12_RESOURCE_DESC buffer_desc{}; + buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer_desc.Width = 256; + buffer_desc.Height = buffer_desc.DepthOrArraySize = buffer_desc.MipLevels = buffer_desc.SampleDesc.Count = 1; + buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ViewAt buffer_view{}; + buffer_view.view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + buffer_view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + buffer_view.view.Buffer.NumElements = 64; + buffer_view.view.Buffer.StructureByteStride = 4; + buffer_view.address = ptr(planes[0].data()); + invoke(guest, 70, ptr(&buffer_desc), ptr(&buffer_view), cpu); + v.address = ptr(planes[0].data()); + invoke(guest, 70, ptr(&desc), ptr(&v), cpu + 1); // Not the start of a descriptor in the view heap. + draw(6); publish(desc, ptr(planes[0].data())); draw(7); return 0; } diff --git a/tests/startup_address_srv_check.py b/tests/startup_address_srv_check.py index 7ede644d6..62a3a5855 100644 --- a/tests/startup_address_srv_check.py +++ b/tests/startup_address_srv_check.py @@ -1,6 +1,7 @@ """Publish two placed R8 textures by address, render their texels, and test rejected updates.""" import os from pathlib import Path +import re import subprocess import sys import tempfile @@ -41,11 +42,43 @@ def draw_texture(directory, consumer, backend, hlsl, modes, view_kind="tex2d", * return output.read_bytes() +R8_RESOURCE = r"res\{dim=3 fmt=61 size=%sx2x1 mips=1 layout=0x0 flags=0x0 align=0 samples=1/0\}" +R8_VIEW = r"view\{dim=4 fmt=61 map=0x1688 mostmip=0 mips=1 plane=0 clamp=0\}" +HEX = r"0x[0-9a-f]+" + + +def check_refusal_lines(log): + """Each refused slot 70 call logs one line with the cause and the fields the checks read.""" + prefix = r"x2w-d3d12 Device::slot70 " + expected = [ + # zero address, wrong width, interior address, buffer view, destination off the heap + prefix + r"unsupported memory SRV arguments: reason=null_address " + R8_RESOURCE % 2 + " " + R8_VIEW + + rf" dest={HEX} dest_in_view_heap=1 address=0x0 address_readable=0", + prefix + r"unavailable texture at the supplied base and layout: reason=texture_unavailable " + R8_RESOURCE % 1 + + " " + R8_VIEW + rf" dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + prefix + r"unavailable texture at the supplied base and layout: reason=texture_unavailable " + R8_RESOURCE % 2 + + " " + R8_VIEW + rf" dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + prefix + r"unsupported memory SRV arguments: reason=unsupported_description " + + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " + + r"view\{dim=1 fmt=0 map=0x1688 first=0 count=64 stride=4 flags=0x0 \(buffer views are not supported\)\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + prefix + r"unsupported memory SRV arguments: reason=destination_outside_view_heaps " + R8_RESOURCE % 2 + " " + + R8_VIEW + rf" dest={HEX} dest_in_view_heap=0 address={HEX} address_readable=1", + ] + lines = [line.rstrip() for line in log.splitlines() if "Device::slot70" in line] + if len(lines) != len(expected): + raise AssertionError(f"{len(lines)} slot 70 lines, expected {len(expected)}:\n" + "\n".join(lines)) + for line, pattern in zip(lines, expected): + if not re.fullmatch(pattern, line): + raise AssertionError(f"slot 70 line does not match\n line {line}\n expected {pattern}") + + def check(directory, consumer, backend): hlsl = ("Texture2D t : register(t0);\n" "float4 main(float4 p : SV_Position) : SV_Target {\n" " return float4(t.Load(int3(uint2(p.xy) % 2, 0)), 0, 0, 1);\n}\n") - actual = draw_texture(directory, consumer, backend, hlsl, {"X2W_TEST_ADDRESS_SRV": "1"}) + trap_log = directory / "trap.log" + actual = draw_texture(directory, consumer, backend, hlsl, {"X2W_TEST_ADDRESS_SRV": "1", "X2W_TRAP_LOG": str(trap_log)}) if actual is None: return 77 plane_at_x = (0, 1, 0, 0, 1, 1, 1, 0) @@ -53,6 +86,7 @@ def check(directory, consumer, backend): for c in (16 + plane * 128 + (y % 2) * 32 + (x % 2) * 7, 0, 0, 255)) if actual != expected: raise AssertionError(f"actual {actual.hex()} expected {expected.hex()}") + check_refusal_lines(trap_log.read_text(errors="replace")) print(f"{backend}: ordinary view, alternating addresses, zero/interior/mismatched updates; all 32 RGBA pixels exact") return 0 diff --git a/tests/startup_memory_srv_report_check.cpp b/tests/startup_memory_srv_report_check.cpp new file mode 100644 index 000000000..bc9241e23 --- /dev/null +++ b/tests/startup_memory_srv_report_check.cpp @@ -0,0 +1,99 @@ +// Checks the diagnostic line of src/startup_stubs/memory_srv_report.h without a device. The expected +// lines are written out by hand: they are what a tester pastes into an issue, field by field. +#include "startup_stubs/memory_srv_report.h" + +#include +#include + +namespace { +int failures; + +void expect(const char* name, const char* actual, const char* expected) +{ + if (std::strcmp(actual, expected) == 0) return; + ++failures; + std::printf("FAIL %s\n actual %s\n expected %s\n", name, actual, expected); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC view(D3D12_SRV_DIMENSION dimension, DXGI_FORMAT format) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = format; + v.ViewDimension = dimension; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + return v; +} + +int line(char (&out)[640], const char* reason, const D3D12_RESOURCE_DESC* r, const D3D12_SHADER_RESOURCE_VIEW_DESC* v, + std::uint64_t address, bool readable, std::uint64_t destination, bool in_heap) +{ + return x2w_startup::report_refused_memory_srv(out, sizeof(out), "unsupported memory SRV arguments", reason, r, v, + address, readable, destination, in_heap); +} +} + +int main() +{ + char out[640]; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 4096; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + + // A view dimension that has no named fields here is printed as its six raw words. + auto as = view(static_cast(11), DXGI_FORMAT_UNKNOWN); + as.Buffer.FirstElement = 0x1122334455667788ull; + line(out, "unsupported_description", &buffer, &as, 0x2000, false, 0x1000, true); + expect("acceleration structure view", out, + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description " + "res{dim=1 fmt=0 size=4096x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0} " + "view{dim=11 fmt=0 map=0x1688 raw=55667788,11223344,00000000,00000000,00000000,00000000 " + "(acceleration structure views are not supported)} dest=0x1000 dest_in_view_heap=1 address=0x2000 address_readable=0"); + + auto b = view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_UNKNOWN); + b.Buffer.FirstElement = 7; + b.Buffer.NumElements = 64; + b.Buffer.StructureByteStride = 16; + b.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + line(out, "unsupported_description", &buffer, &b, 0x2000, true, 0x1000, true); + expect("buffer view", out, + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description " + "res{dim=1 fmt=0 size=4096x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0} " + "view{dim=1 fmt=0 map=0x1688 first=7 count=64 stride=16 flags=0x1 (buffer views are not supported)} " + "dest=0x1000 dest_in_view_heap=1 address=0x2000 address_readable=1"); + + D3D12_RESOURCE_DESC bc7{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 65536, 128, 128, 2, 6, DXGI_FORMAT_BC7_UNORM, {1, 0}, + static_cast(0x105), static_cast(0x300000)}; + auto array = view(D3D12_SRV_DIMENSION_TEXTURE2DARRAY, DXGI_FORMAT_BC7_UNORM); + array.Texture2DArray.MostDetailedMip = 1; + array.Texture2DArray.MipLevels = 5; + array.Texture2DArray.FirstArraySlice = 1; + array.Texture2DArray.ArraySize = 1; + array.Texture2DArray.ResourceMinLODClamp = 0.5f; + line(out, "destination_outside_view_heaps", &bc7, &array, 0x7000, true, 0x1001, false); + expect("texture array view", out, + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=destination_outside_view_heaps " + "res{dim=3 fmt=98 size=128x128x2 mips=6 layout=0x105 flags=0x300000 align=65536 samples=1/0} " + "view{dim=5 fmt=98 map=0x1688 mostmip=1 mips=5 first=1 count=1 plane=0 clamp=0.5} " + "dest=0x1001 dest_in_view_heap=0 address=0x7000 address_readable=1"); + + // Memory the guest handed over but the runtime could not read. + line(out, "null_destination", nullptr, nullptr, 0, false, 0, false); + expect("unreadable arguments", out, + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=null_destination " + "res{unreadable} view{unreadable} dest=0x0 dest_in_view_heap=0 address=0x0 address_readable=0"); + + // A small buffer is cut, never overrun, and stays terminated. + char small[40]; + std::memset(small, 'x', sizeof(small)); + x2w_startup::report_refused_memory_srv(small, sizeof(small), "unsupported memory SRV arguments", "null_address", &bc7, + &array, 0, false, 0x1000, true); + if (std::memchr(small, 0, sizeof(small)) == nullptr) { + ++failures; + std::printf("FAIL truncated line is not terminated\n"); + } + if (failures) return 1; + std::printf("slot 70 refusal lines: 4 formats and a truncation exact\n"); + return 0; +} From 64b6d2d32545e4de6cdb3c1df4a07ed77564a217 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:11:00 +0100 Subject: [PATCH 017/775] fix: return ApuFree blocks to the APU heap stand-in through a coalescing free list --- CMakeLists.txt | 6 + docs/experiments.md | 4 + docs/startup-runtime.md | 23 +++ src/startup_stubs/acphal.cpp | 115 +++++++++++-- tests/startup_acphal_apu_free.cpp | 273 ++++++++++++++++++++++++++++++ 5 files changed, 407 insertions(+), 14 deletions(-) create mode 100644 tests/startup_acphal_apu_free.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0acbae4b7..d88b39bc9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -335,6 +335,12 @@ target_include_directories(startup_storage_file_range PRIVATE src) add_test(NAME startup_storage_file_range COMMAND startup_storage_file_range) target_compile_features(startup_stub_consumer PRIVATE cxx_std_17) target_link_libraries(startup_stub_consumer PRIVATE startup_stub_chad startup_stub_xg_xs xmem_shim d3d12_xs_shim) +# APU heap stand-in: ApuFree reuse, coalescing, refused requests and concurrent callers (docs/startup-runtime.md). +add_executable(startup_acphal_apu_free tests/startup_acphal_apu_free.cpp) +target_compile_features(startup_acphal_apu_free PRIVATE cxx_std_17) +add_dependencies(startup_acphal_apu_free startup_stub_acphal) +add_test(NAME startup_acphal_apu_free COMMAND startup_acphal_apu_free "$") +set_tests_properties(startup_acphal_apu_free PROPERTIES TIMEOUT 60) add_executable(startup_draw_bmp_check tests/startup_draw_bmp.cpp) add_test(NAME startup_draw_bmp COMMAND startup_draw_bmp_check) diff --git a/docs/experiments.md b/docs/experiments.md index 2712f4d85..3de0100f4 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6779,6 +6779,10 @@ On success the caller exits with `0x8AC`, also with `CPU_CRC_TEST_LIVE_WORKER=1` ctest --preset dev --no-tests=error -R '^cpu_native_acphal_hal$' -V ctest --preset release --no-tests=error -R '^cpu_native_acphal_hal$' -V +### ApuFree in the AcpHal stand-in + +The desktop `AcpHal.dll` stand-in (not the fixture provider above) now returns `ApuAlloc` blocks on `ApuFree` through a first-fit free list with coalescing, so repeated allocate and free cycles no longer exhaust the heap. It is a stand-in contract only: the console's error codes, alignment limits and zero-size behaviour are not public, and the codes chosen are listed in [startup-runtime.md](startup-runtime.md#apu-heap-stand-in). The source-built check is `ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V`. + ### XApu command-queue caller and recorder A source-built caller ([`xapu_queue_caller.asm`](../tests/cpu/xapu_queue_caller.asm)) imports the five `xapu.dll` command-queue functions by name (`XApuConnect`, `XApuEnqueueCommand`, `XApuGetResultCount`, `XApuDequeueResult`, `XApuDisconnect`), plus `finish_exe` from `cpu_exe_io.dll`, and starts through [`exe_startup.asm`](../tests/cpu/exe_startup.asm). A test-only recording provider ([`xapu_queue_provider.cpp`](../tests/cpu/xapu_queue_provider.cpp)) serves the five names. This is not a production `xapu.dll`, and this change adds no binding. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index e4667a900..de00907dd 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -463,6 +463,29 @@ format and Windows build. A skip is neither a pass nor a failure. Every wait is Not established: the layout of the console audio command queue (`xapu.cpp` is not decoded here), what is audible (no capture-path check), and any hardware or driver glitch count. +## APU heap stand-in + +With `X2W_AUDIO_PERMISSIVE=1`, `AcpHal.dll` serves `ApuAlloc` from the heap that `ApuCreateHeap` commits. The +heap is a first-fit free list in a static table of 4096 extents, guarded by one lock. `ApuFree` gives a +block back and merges it with free neighbours, so streaming code that allocates and frees repeatedly no +longer exhausts the heap. While nothing has been freed the offsets are the ones a bump allocator hands out. + +- A block is aligned in address (a power of two, 16 at least; 0 means 16). Size and alignment are 32 bits. +- Null output is `E_POINTER`; size 0 or an alignment that is not a power of two is `E_INVALIDARG`; no + room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and its outputs as they were. +- A block that is reused is zeroed, as fresh heap memory is. +- `ApuFree(NULL)` is `S_OK`. An address that does not start a live block (never allocated, inside a block, + already freed) is `E_INVALIDARG` and changes nothing. +- `ApuIsVirtualAddressValid` and the two map calls still test the whole heap range, not live blocks. + +The shape-context allocation (`AcpHalAllocateShapeContexts`, types other than 4) is unchanged. The source-built +check loads the stub, cycles 64 MiB through a 2 MiB heap, checks reuse, alignment, coalescing and every refused +call, then runs 4 threads of 1000 rounds against an interval map of live blocks: + +``` +ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V +``` + ## Uniform first-lane reads The startup shader translator accepts `v_readfirstlane_b32` in straight-line code with the diff --git a/src/startup_stubs/acphal.cpp b/src/startup_stubs/acphal.cpp index bbcc3f620..6099de64d 100644 --- a/src/startup_stubs/acphal.cpp +++ b/src/startup_stubs/acphal.cpp @@ -18,23 +18,98 @@ using u64 = std::uint64_t; bool permissive() noexcept { return x2w_local::env_on("X2W_AUDIO_PERMISSIVE"); } -// APU heap: one committed region; an APU address is an offset into it. A bump allocator serves the -// context arrays (and later ApuAlloc, once its call shape is seen). +// APU heap: one committed region; an APU address is an offset into it. A table of extents, sorted by +// offset, tiles [heap_start, heap_bytes) and each extent is free or used. Allocation is first-fit in +// address order, so while nothing has been freed it hands out the same offsets a bump allocator would; +// a freed extent is merged with free neighbours. The table is static: when it is full a request that +// needs a split fails like an exhausted heap. All state is guarded by heap_lock. +constexpr u64 heap_start = 0x10000; // APU address 0 stays unused +constexpr std::size_t max_extents = 4096; +struct Extent { + u64 start, size; + bool used; +}; unsigned char* heap_base; u64 heap_bytes; -u64 heap_used; +Extent extents[max_extents]; +std::size_t extent_count; +u64 high_water; // offsets below this were handed out once and may hold old data SRWLOCK heap_lock = SRWLOCK_INIT; +void heap_reset() noexcept +{ + extent_count = 0; + if (heap_bytes > heap_start) extents[extent_count++] = {heap_start, heap_bytes - heap_start, false}; + high_water = heap_start; +} + +// bytes and alignment (a power of two) are checked by the callers; both stay far below 2^63. unsigned char* heap_take(u64 bytes, u64 alignment) { + unsigned char* result = nullptr; + u64 zero_from = 0, zero_bytes = 0; AcquireSRWLockExclusive(&heap_lock); - const u64 start = (heap_used + alignment - 1) & ~(alignment - 1); - unsigned char* result = heap_base && start + bytes <= heap_bytes ? heap_base + start : nullptr; - if (result) heap_used = start + bytes; + for (std::size_t i = 0; heap_base && i < extent_count && !result; ++i) { + const Extent e = extents[i]; + const u64 address_low = (reinterpret_cast(heap_base) + e.start) & (alignment - 1); + const u64 pad = (alignment - address_low) & (alignment - 1); + if (e.used || pad > e.size || bytes > e.size - pad) continue; + const u64 tail = e.size - pad - bytes; + const std::size_t extra = (pad ? 1 : 0) + (tail ? 1 : 0); + if (extent_count + extra > max_extents) continue; + std::memmove(&extents[i + 1 + extra], &extents[i + 1], (extent_count - i - 1) * sizeof(Extent)); + std::size_t at = i; + if (pad) extents[at++] = {e.start, pad, false}; + extents[at++] = {e.start + pad, bytes, true}; + if (tail) extents[at] = {e.start + pad + bytes, tail, false}; + extent_count += extra; + result = heap_base + e.start + pad; + const u64 end = e.start + pad + bytes; + if (e.start + pad < high_water) { + zero_from = e.start + pad; + zero_bytes = (end < high_water ? end : high_water) - zero_from; + } + if (end > high_water) high_water = end; + } ReleaseSRWLockExclusive(&heap_lock); + if (zero_bytes) std::memset(heap_base + zero_from, 0, static_cast(zero_bytes)); // fresh pages are zero return result; } +// Gives back the used extent that starts exactly at virtual_address. Anything else (outside the heap, +// inside a block, already free) is refused and leaves the table unchanged. +bool heap_give(const void* virtual_address) +{ + bool done = false; + const std::uintptr_t address = reinterpret_cast(virtual_address); + const std::uintptr_t base = reinterpret_cast(heap_base); + AcquireSRWLockExclusive(&heap_lock); + if (heap_base && address >= base + heap_start && address - base < heap_bytes) { + const u64 offset = address - base; + std::size_t lo = 0, hi = extent_count; + while (lo < hi) { + const std::size_t mid = (lo + hi) / 2; + if (extents[mid].start < offset) lo = mid + 1; else hi = mid; + } + if (lo < extent_count && extents[lo].start == offset && extents[lo].used) { + extents[lo].used = false; + if (lo + 1 < extent_count && !extents[lo + 1].used) { + extents[lo].size += extents[lo + 1].size; + std::memmove(&extents[lo + 1], &extents[lo + 2], (extent_count - lo - 2) * sizeof(Extent)); + --extent_count; + } + if (lo > 0 && !extents[lo - 1].used) { + extents[lo - 1].size += extents[lo].size; + std::memmove(&extents[lo], &extents[lo + 1], (extent_count - lo - 1) * sizeof(Extent)); + --extent_count; + } + done = true; + } + } + ReleaseSRWLockExclusive(&heap_lock); + return done; +} + // AcpHal object (not COM: slot 0 is the first method). Seen: slot 0 (0x1000, 0x1000) -> HRESULT, a // connect with two queue lengths; slot 2 (type, id, frame, &value, 0) -> HRESULT, a command submit. // Both succeed and are logged; every other slot traps and names itself. @@ -77,8 +152,10 @@ extern "C" __declspec(noinline) long ApuCreateHeap(u64 rcx, u64 rdx, u64 r8, u64 if (!heap_base) { const u64 bytes = ((cached + non_cached) + 0xFFFF) & ~u64{0xFFFF}; heap_base = static_cast(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + AcquireSRWLockExclusive(&heap_lock); heap_bytes = heap_base ? bytes : 0; - heap_used = 0x10000; // APU address 0 stays unused + heap_reset(); + ReleaseSRWLockExclusive(&heap_lock); if (!heap_base) hr = static_cast(0x8007000E); // E_OUTOFMEMORY } x2w_local::logf("x2w-audio ApuCreateHeap cached=0x%llx non_cached=0x%llx -> 0x%08lx base=%p", cached, non_cached, @@ -139,7 +216,10 @@ extern "C" __declspec(noinline) long AcpHalCreate(u64 rcx, u64 rdx, u64 r8, u64 } // ApuAlloc(&virtualAddress, apuAddress* or null, size, alignment, flags) -> HRESULT (first call: -// size 0x222e00, alignment 0x800, null APU-address output). Bump allocation; nothing is reused. +// size 0x222e00, alignment 0x800, null APU-address output). Size and alignment are taken as 32 bits. +// First fit; ApuFree returns blocks, and a reused block is zeroed as fresh heap memory is. +// A null output is E_POINTER, size 0 or an alignment that is not a power of two is E_INVALIDARG +// (0 and anything below 16 mean 16), and no room is E_OUTOFMEMORY; a failure leaves the heap as it was. extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint32_t* apu_address, u64 size, u64 alignment, u64 flags) { @@ -148,9 +228,10 @@ extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint3 reinterpret_cast(apu_address), size, alignment, _ReturnAddress()); const u64 bytes = static_cast(size); u64 align = static_cast(alignment); - if (align < 16 || (align & (align - 1))) align = 16; - unsigned char* memory = virtual_address ? heap_take(bytes, align) : nullptr; - const long hr = memory ? 0 : static_cast(virtual_address ? 0x8007000E : 0x80004003); + if (align < 16) align = 16; + const bool valid = bytes && !(align & (align - 1)); + unsigned char* memory = virtual_address && valid ? heap_take(bytes, align) : nullptr; + const long hr = memory ? 0 : static_cast(!virtual_address ? 0x80004003 : valid ? 0x8007000E : 0x80070057); if (virtual_address) *virtual_address = memory; if (memory && apu_address) *apu_address = static_cast(memory - heap_base); static LONG calls; @@ -161,17 +242,23 @@ extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint3 return hr; } -// The four below take their shapes from their names; none has been seen yet, so each logs its first calls. +// ApuFree(virtualAddress) -> HRESULT (every known caller discards it). Null is a no-op and S_OK; an address +// that is not the start of a live block (unknown, inside a block, already freed) is E_INVALIDARG. extern "C" __declspec(noinline) long ApuFree(void* virtual_address) { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuFree", 5, reinterpret_cast(virtual_address), 0, 0, 0, _ReturnAddress()); + if (!virtual_address) return 0; + const long hr = heap_give(virtual_address) ? 0 : static_cast(0x80070057); static LONG calls; - if (x2w_local::first_calls(calls, 4)) x2w_local::logf("x2w-audio ApuFree %p (not reused)", virtual_address); - return 0; + if (FAILED(hr) || x2w_local::first_calls(calls, 4)) + x2w_local::logf("x2w-audio ApuFree %p -> 0x%08lx", virtual_address, static_cast(hr)); + return hr; } +// The three below take their shapes from their names; none has been seen yet, so each logs its first calls. + extern "C" __declspec(noinline) int ApuIsVirtualAddressValid(void* virtual_address) { if (!permissive()) diff --git a/tests/startup_acphal_apu_free.cpp b/tests/startup_acphal_apu_free.cpp new file mode 100644 index 000000000..f716dacd8 --- /dev/null +++ b/tests/startup_acphal_apu_free.cpp @@ -0,0 +1,273 @@ +// Source-built check of the AcpHal stand-in APU heap (src/startup_stubs/acphal.cpp): ApuFree returns blocks, +// neighbours coalesce, bad requests leave the heap alone and concurrent callers never get overlapping blocks. +// Usage: startup_acphal_apu_free +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using u64 = std::uint64_t; +using AllocFn = long(__cdecl*)(void**, std::uint32_t*, u64, u64, u64); +using FreeFn = long(__cdecl*)(void*); +using CreateFn = long(__cdecl*)(u64, u64); +using MapFn = std::uint32_t(__cdecl*)(void*); + +constexpr long ok = 0, invalid = static_cast(0x80070057), no_memory = static_cast(0x8007000E), + no_pointer = static_cast(0x80004003); +constexpr u64 heap_size = 0x200000, first_offset = 0x10000, usable = heap_size - first_offset; + +AllocFn alloc_fn; +FreeFn free_fn; +MapFn map_fn; +int failures; + +void check(bool condition, const char* what) +{ + if (condition) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +long take(void** out, u64 size, u64 alignment = 16, std::uint32_t* apu = nullptr) { return alloc_fn(out, apu, size, alignment, 0); } + +void* take_ok(u64 size, u64 alignment = 16) +{ + void* p = nullptr; + const long hr = take(&p, size, alignment); + check(hr == ok && p, "allocation succeeds"); + return p; +} + +// The whole heap is free again exactly when one block of the full usable size fits at the first offset. +void check_empty(const char* where) +{ + std::uint32_t apu = 0; + void* p = nullptr; + const long hr = take(&p, usable, 16, &apu); + if (hr != ok || !p || apu != first_offset) { + std::printf("FAIL: heap not whole after %s (hr=0x%08lx apu=0x%x)\n", where, static_cast(hr), apu); + ++failures; + return; + } + check(free_fn(p) == ok, "whole-heap block frees"); +} + +void churn_beyond_capacity() +{ + void* a = take_ok(0x100000, 4096); + void* b = nullptr; + check(take(&b, 0x100000, 4096) == no_memory && !b, "two 1 MiB blocks do not fit while the first is live"); + check(free_fn(a) == ok, "free first"); + for (int round = 0; round < 64; ++round) { // 64 MiB handed out in total, over 30 times the heap + void* p = take_ok(0x100000, 4096); + check(p == a, "same block comes back"); + if (!p) return; + check(free_fn(p) == ok, "churn free"); + } + check_empty("churn"); +} + +void reuse_and_alignment() +{ + for (u64 alignment : {16u, 256u, 4096u, 65536u}) { + void* keep = take_ok(0x30, 16); + void* a = take_ok(0x2000, alignment); + void* after = take_ok(0x30, 16); + check(reinterpret_cast(a) % alignment == 0, "alignment honoured"); + std::memset(a, 0xAA, 0x2000); + check(free_fn(a) == ok, "free"); + void* again = take_ok(0x2000, alignment); + check(again == a, "same size returns the freed block"); + bool zero = true; + for (int i = 0; i < 0x2000; ++i) zero = zero && static_cast(again)[i] == 0; + check(zero, "reused block is zeroed like fresh heap memory"); + check(free_fn(again) == ok, "free again"); + void* smaller = take_ok(0x1000, alignment); + check(smaller >= a && static_cast(smaller) + 0x1000 <= static_cast(a) + 0x2000, + "smaller request lands inside the freed block"); + std::uint32_t apu = 0; + void* mapped = nullptr; + check(take(&mapped, 0x40, 64, &apu) == ok && map_fn(mapped) == apu && apu, "APU address maps back to the block"); + for (void* p : {keep, after, smaller, mapped}) check(free_fn(p) == ok, "cleanup free"); + check_empty("reuse"); + } +} + +void coalescing() +{ + constexpr u64 part = 0x10000; + void* a = take_ok(part); + void* b = take_ok(part); + void* c = take_ok(part); + void* rest = take_ok(usable - 3 * part); // fills the heap: only A, B, C can ever be free + auto* base = static_cast(a); + check(b == base + part && c == base + 2 * part, "A, B and C are contiguous"); + check(free_fn(a) == ok && free_fn(c) == ok, "free A and C"); + void* big = nullptr; + check(take(&big, 3 * part) == no_memory && !big, "A+B+C does not fit while B is live"); + check(free_fn(b) == ok, "free B"); + big = take_ok(3 * part); + check(big == a, "A+B+C is one block at A"); + check(free_fn(big) == ok && free_fn(rest) == ok, "cleanup"); + check_empty("coalescing"); + void* x = take_ok(part); // reverse order, middle first + void* y = take_ok(part); + void* z = take_ok(part); + check(free_fn(y) == ok && free_fn(z) == ok && free_fn(x) == ok, "free middle, last, first"); + check_empty("coalescing reverse"); +} + +void bad_requests() +{ + const void* const sentinel = reinterpret_cast(0x1234); + void* out = const_cast(sentinel); + std::uint32_t apu = 0xDEADBEEF; + check(free_fn(nullptr) == ok, "free(null) is a no-op"); + check(take(nullptr, 64) == no_pointer, "null output"); + check(take(&out, usable + 16, 16, &apu) == no_memory && !out && apu == 0xDEADBEEF, "larger than the heap"); + out = const_cast(sentinel); + check(take(&out, 0xFFFFFFFFull, 16, &apu) == no_memory && !out, "size near 2^32"); + check(take(&out, ~u64{0}, 16, &apu) == no_memory && !out, "size 2^64-1 is cut to 32 bits"); + check(take(&out, 0, 16, &apu) == invalid && !out && apu == 0xDEADBEEF, "size 0"); + check(take(&out, 0x100000000ull, 16, &apu) == invalid && !out, "size 2^32 is size 0"); + check(take(&out, 64, 24, &apu) == invalid && !out && apu == 0xDEADBEEF, "alignment 24"); + check(take(&out, 64, 0xFFFFFFFFull, &apu) == invalid && !out, "alignment 2^32-1"); + check(take(&out, 64, 0x80000000ull, &apu) == no_memory && !out, "alignment 2 GiB cannot be met"); + check_empty("refused requests"); + + void* p = take_ok(0x40, 0); // 0 means the default of 16 + check(reinterpret_cast(p) % 16 == 0, "alignment 0"); + void* q = take_ok(0x40, 4); + check(reinterpret_cast(q) % 16 == 0, "alignment 4 is raised to 16"); + check(free_fn(static_cast(p) + 8) == invalid, "free inside a live block"); + check(free_fn(&failures) == invalid, "free of a foreign address"); + check(free_fn(reinterpret_cast(0x10)) == invalid, "free of a tiny address"); + check(free_fn(p) == ok, "free"); + check(free_fn(p) == invalid, "double free"); + void* big = nullptr; + check(take(&big, usable) == no_memory, "q is still live after the refused frees"); + check(free_fn(q) == ok && free_fn(q) == invalid, "free q, then a double free"); + check_empty("refused frees"); +} + +void table_full() +{ + std::vector blocks; + void* p = nullptr; + while (blocks.size() < 5000 && take(&p, 256) == ok) blocks.push_back(p); + check(blocks.size() < 5000 && blocks.size() * 256 < usable, "extent table limit refuses before the heap is full"); + check(!blocks.empty() && take(&p, 256) == no_memory && !p, "refusal is E_OUTOFMEMORY and repeatable"); + for (size_t i = 0; i < blocks.size(); i += 2) check(free_fn(blocks[i]) == ok, "free every other block"); + for (size_t i = 1; i < blocks.size(); i += 2) check(free_fn(blocks[i]) == ok, "free the rest"); + check_empty("table full"); +} + +// Deterministic generator, so a failure is reproducible. +struct Rng { + std::uint32_t state; + std::uint32_t next() { return state = state * 1664525u + 1013904223u; } +}; + +struct Live { + std::map blocks; // start -> end, shared by all threads + std::mutex lock; + bool add(std::uintptr_t start, std::uintptr_t end) + { + std::lock_guard guard(lock); + auto next = blocks.lower_bound(start); + if (next != blocks.end() && next->first < end) return false; + if (next != blocks.begin() && std::prev(next)->second > start) return false; + blocks[start] = end; + return true; + } + void remove(std::uintptr_t start) + { + std::lock_guard guard(lock); + blocks.erase(start); + } +}; + +void worker(unsigned id, unsigned rounds, std::atomic* ready, std::atomic* errors, Live* live) +{ + struct Mine { + unsigned char* p; + u64 size; + unsigned char tag; + }; + std::vector mine; + Rng rng{0xC0FFEEu + id * 7919u}; + ready->fetch_add(1); + while (ready->load() < 4) {} + auto release = [&](std::size_t index) { + const Mine m = mine[index]; + for (u64 i = 0; i < m.size; ++i) + if (m.p[i] != m.tag) { errors->fetch_add(1); break; } + live->remove(reinterpret_cast(m.p)); + if (free_fn(m.p) != ok) errors->fetch_add(1); + mine.erase(mine.begin() + static_cast(index)); + }; + for (unsigned round = 0; round < rounds; ++round) { + if (mine.size() >= 12 || (!mine.empty() && rng.next() % 3 == 0)) release(rng.next() % mine.size()); + const u64 size = 16 + (rng.next() % 256) * 16; + const u64 alignment = u64{16} << (rng.next() % 5); + void* p = nullptr; + if (take(&p, size, alignment) != ok || !p || reinterpret_cast(p) % alignment) { + errors->fetch_add(1); + continue; + } + const auto start = reinterpret_cast(p); + if (!live->add(start, start + size)) errors->fetch_add(1); + const unsigned char tag = static_cast(id * 64 + round % 61 + 1); + std::memset(p, tag, size); + mine.push_back({static_cast(p), size, tag}); + } + while (!mine.empty()) release(mine.size() - 1); +} + +void concurrent() +{ + Live live; + std::atomic ready{0}, errors{0}; + std::vector threads; + for (unsigned id = 0; id < 4; ++id) threads.emplace_back(worker, id, 1000u, &ready, &errors, &live); + for (auto& t : threads) t.join(); + check(errors.load() == 0, "no overlap, torn pattern or unexpected error across 4 threads x 1000 rounds"); + check(live.blocks.empty(), "every block was released"); + check_empty("concurrent run"); +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return std::printf("usage: startup_acphal_apu_free \n"), 2; + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); + HMODULE module = LoadLibraryA(argv[1]); + if (!module) return std::printf("FAIL: cannot load %s\n", argv[1]), 2; + alloc_fn = reinterpret_cast(GetProcAddress(module, "ApuAlloc")); + free_fn = reinterpret_cast(GetProcAddress(module, "ApuFree")); + map_fn = reinterpret_cast(GetProcAddress(module, "ApuMapVirtualAddress")); + auto create = reinterpret_cast(GetProcAddress(module, "ApuCreateHeap")); + if (!alloc_fn || !free_fn || !map_fn || !create) return std::printf("FAIL: missing export\n"), 2; + void* none = nullptr; + check(take(&none, 64) == no_memory && !none, "no heap yet"); + check(create(heap_size, 0) == ok, "ApuCreateHeap"); + churn_beyond_capacity(); + reuse_and_alignment(); + coalescing(); + bad_requests(); + table_full(); + concurrent(); + std::printf(failures ? "startup_acphal_apu_free: %d failure(s)\n" : "startup_acphal_apu_free: ok\n", failures); + return failures ? 1 : 0; +} From dc70f46ba4e563c8afba75e96e79ab1effcc9364 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 19:14:15 +0800 Subject: [PATCH 018/775] shader: lower gfx1030 2D image resource queries --- CMakeLists.txt | 5 +++ README.md | 1 + docs/experiments.md | 23 +++++++++++ tests/compute_store_check.py | 77 ++++++++++++++++++++++++++++++++++++ tools/compute_store_aot.py | 43 +++++++++++++------- 5 files changed, 134 insertions(+), 15 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0acbae4b7..0ce4aa7c6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5450,6 +5450,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mimg_mip_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mimg_mip_${adapter}.txt") + add_test(NAME compute_store_aot_mimg_resinfo_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mimg-resinfo "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_mimg_resinfo_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mimg_resinfo_${adapter}.txt") add_test(NAME compute_store_aot_mimg_packed_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mimg-packed "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index c8063314c..75dad6a6e 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 atomic buffer reductions | Lower [fixed-address MUBUF integer reductions](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-reductions) and verify the final value under lane contention. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_reduction_'` | | gfx1030 raw vector reads | Lower [indexed `buffer_load_dwordx2/x3/x4`](docs/experiments.md#indexed-gfx1030-raw-vector-reads) and verify channel order, destination/index aliasing and untouched output. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_vector_'` | | gfx1030 image loads | Lower [typed RGBA32 and packed RGBA8 2D reads](docs/experiments.md#gfx1030-2d-image-loads), including explicit mip levels, with 32-bit or `a16` addresses and nonzero `dmask` values. Compare the UAV readback against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_(load|mip|packed)_'` | +| gfx1030 image queries | Lower [2D mip dimensions and level count](docs/experiments.md#gfx1030-2d-image-resource-queries) for `image_get_resinfo`. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_resinfo_'` | | gfx1030 image stores | Lower [typed RGBA32 and packed RGBA8 2D writes](docs/experiments.md#gfx1030-2d-image-stores), including fixed explicit mip levels and sparse `dmask` values. Compare all mip levels against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_store_'` | | gfx1030 formatted D16 UINT reads | Lower [indexed `buffer_load_format_d16_*` with caller-declared RGBA16 UINT](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-reads) and verify packed channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_load_format_d16_'` | | gfx1030 raw D16 reads | Lower [indexed D16 byte and short MUBUF loads](docs/experiments.md#indexed-gfx1030-raw-d16-reads) and verify that the other VGPR half stays unchanged. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_d16_'` | diff --git a/docs/experiments.md b/docs/experiments.md index 2712f4d85..b5c18b7de 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3102,6 +3102,29 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_packed_(warp|hardware)$' -V ``` +### gfx1030 2D image resource queries + +`image_get_resinfo` lowers to `Texture2D.GetDimensions` on the +`R32G32B32A32_UINT` SRV at `t0`. Supply `--image-descriptor` and `--image-format` +as for typed loads. The address is one VGPR holding an in-range mip index +relative to the start of the view. `a16` takes the low 16 bits of that VGPR. +DMASK selects width, height and view mip count in ascending bit order. This +2D profile rejects the depth bit, unmodelled flags, and non-2D dimensions. +The descriptor needs `s_waitcnt lgkmcnt(0)` and the results need +`s_waitcnt vmcnt(0)`. The mip operand may alias a destination register. + +The 14 cases assemble and disassemble with LLVM 15, then pass through the +synthetic-container CLI. The GPU fixture compares translated desktop DXIL +against a CPU reference for mips 0, 1 and 2, one- and three-level views, +both address widths, sparse masks and one, two or four groups. It compares all 320 output words per case, +including padding. Forcing mip 0 first differs at word 32, where the expected +width is `00000010` and the actual width is `00000020`. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_resinfo_(warp|hardware)$' -V +``` + ### gfx1030 2D image stores `image_store`, `image_store_mip`, `image_store_pck` and `image_store_mip_pck` diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index 5481c566b..ee8ff1177 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -3327,6 +3327,10 @@ def binary(directory, assembler, objcopy, library): ds_binary(directory, assembler, objcopy, library) mtbuf_load_controls() mimg_load_binary(directory, assembler, objcopy, library) + mimg_resinfo_controls() + gfx1030_binary(directory, assembler, objcopy, library, + [(name, lines, MIMG_BINDING) for name, _, _, _, _, lines in mimg_resinfo_cases()], + "image_get_resinfo", group=(8, 8, 1)) mimg_store_controls() gfx1030_binary(directory, assembler, objcopy, library, [(name, lines, binding) for name, _, _, lines, binding in mimg_store_cases()], @@ -4719,6 +4723,78 @@ def mimg_store_draw(directory, compiler, renderer, backend, *, packed=False): return 0 +def mimg_resinfo_cases(): + for a16 in (False, True): + for mask, channels, groups, shift, lines in mimg_load_cases(): + if mask & 0x4: + continue + # Use one mip operand, with nonzero upper padding for a16. v14 is also the first result. + levels = 1 if mask == 0x8 else 3 + query = f"v_min_u32_e32 v14, {levels - 1}, v9" + if a16: + query += "\nv_or_b32_e32 v14, 0xabcd0000, v14" + image = next(line for line in lines if line.startswith("image_load ")) + replacement = image.replace("image_load", "image_get_resinfo").replace("v[8:9]", "v14") + if a16: + replacement += " unorm a16" + name = f"mimg_resinfo{int(a16)}_{mask:x}" + yield name, channels, groups, shift, levels, variant(lines, (image, f"{query}\n{replacement}")) + + +def mimg_resinfo_controls(): + _, _, _, _, _, lines = next(mimg_resinfo_cases()) + for diagnostic, change in ( + ("Unresolved image descriptor", ("s_waitcnt lgkmcnt(0)", "")), + ("before s_waitcnt vmcnt(0)", ("s_waitcnt vmcnt(0)", "")), + ("Unverified image coordinates", ("v14, v14, s[24:31]", "v14, v15, s[24:31]")), + ("Unsupported image get_resinfo target", ("v14, v14, s[24:31]", "v14, v[14:15], s[24:31]")), + ("Unsupported image get_resinfo target", ("dmask:0x1", "dmask:0x4")), + ("Unsupported compute instruction", ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_3D")), + ): + rejects(diagnostic, aot.lower, variant(lines, change), (8, 8, 1), **MIMG_BINDING) + rejects("Image get_resinfo requires an RGBA32 SRV", aot.lower, lines, (8, 8, 1), **MIMG_PACKED_BINDING) + + +def mimg_resinfo_draw(directory, compiler, renderer, backend): + mimg_resinfo_controls() + base_texture = [word for texel in TEXTURE_WORDS for word in texel] + for name, channels, groups, shift, levels, lines in mimg_resinfo_cases(): + texture = base_texture if levels == 1 else base_texture + mimg_mip_texels() + payload = struct.pack(f"<{len(texture)}I", *texture) + src, cso, case = (directory / f"{name}.{ext}" for ext in ("hlsl", "cso", "case")) + code = aot.lower(lines, (8, 8, 1), **MIMG_BINDING) + expected = [SENTINEL] * 320 + for y in range(TEXTURE_HEIGHT): + width, height = ((32, 8), (16, 4), (8, 2))[min(y, levels - 1)] + components = {0: width, 1: height, 3: levels} + for x in range(groups * 8): + base = y * 32 + x * (1 << (shift - 2)) + expected[base:base + len(channels)] = [components[channel] for channel in channels] + case.write_bytes(struct.pack("<321I", groups, *expected) + payload) + compile_shader = [compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src] + run = [renderer, backend, "--compute-texture-case", cso, case] + src.write_text(code, encoding="ascii") + subprocess.run(compile_shader, check=True) + result = subprocess.run(run) + if result.returncode: + return result.returncode + if name == "mimg_resinfo1_b": + mutant = code.replace("imageData.GetDimensions((", "imageData.GetDimensions(0u * (") + assert mutant != code + src.write_text(mutant, encoding="ascii") + subprocess.run(compile_shader, check=True) + bad = subprocess.run(run, capture_output=True, text=True) + mismatch = "word=32 expected=00000010 actual=00000020" + if bad.returncode != 1 or mismatch not in bad.stderr: + raise AssertionError(f"{name}: fixed mip escaped detection\n{bad.stderr}") + print(f"{name} fixed mip: {bad.stderr}", end="") + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("image_get_resinfo\n", encoding="utf-8") + return 0 + + def mimg_mip_draw(directory, compiler, renderer, backend): return mimg_load_draw(directory, compiler, renderer, backend, mip=True) @@ -5393,6 +5469,7 @@ def draw(directory, compiler, renderer, backend, cases=None): "draw-mtbuf-load": mtbuf_load_draw, "draw-mimg-load": mimg_load_draw, "draw-mimg-mip": mimg_mip_draw, + "draw-mimg-resinfo": mimg_resinfo_draw, "draw-mimg-packed": mimg_packed_draw, "draw-mimg-store": mimg_store_draw, "draw-mimg-packed-store": lambda d, *a: mimg_store_draw(d, *a, packed=True), diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index 14b226ac8..e28130767 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -1189,15 +1189,16 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("D16 buffer read expression is too large") word = ("alu", field) loading[reg] = word - elif m := re.fullmatch(r"image_(?Pload|store)(?P_mip)?(?P_pck(?:_sgn)?)? " + elif m := re.fullmatch(r"image_(?Pload|store|get_resinfo)(?P_mip)?(?P_pck(?:_sgn)?)? " r"(?Pv\d+|v\[\d+:\d+\]), (?Pv\d+|v\[\d+:\d+\]), " r"s\[(?P\d+):(?P\d+)\] dmask:0x(?P[0-9a-f]+) " r"dim:SQ_RSRC_IMG_2D(?: unorm)?(?P a16)?", line): # A16 packs x/y into one dword and takes the mip from the low half of the next dword. mip, a16 = bool(m["mip"]), bool(m["a16"]) write = m["kind"] == "store" + resinfo = m["kind"] == "get_resinfo" vaddr = [int(n) for n in re.findall(r"\d+", m["addr"])] - address_words = (1 if a16 else 2) + int(mip) + address_words = 1 if resinfo else (1 if a16 else 2) + int(mip) base, high = int(m["base"]), int(m["high"]) dmask = int(m["mask"], 16) # DMASK selects components in XYZW order and packs them into consecutive VGPRs. @@ -1210,8 +1211,11 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N or vaddr[-1] > 255 or last != first + count - 1 or not 0 < dmask < (1 << IMAGE_FORMATS[image_format][1]) or any(first + index > 255 or first + index in loading for index in range(count)) - or (write and (m["packed"] == "_pck_sgn" or stores))): + or (write and (m["packed"] == "_pck_sgn" or stores)) + or (resinfo and (mip or m["packed"] or dmask & 0x4))): raise ValueError(f"Unsupported image {m['kind']} target") + if resinfo and image_format != "R32G32B32A32_UINT": + raise ValueError("Image get_resinfo requires an RGBA32 SRV") if bool(m["packed"]) != (image_format == "R8G8B8A8_UINT"): raise ValueError(f"Image {m['kind']} opcode does not match the image format") if high != base + 7 or base % 4 or pending.intersection(range(base, high + 1)): @@ -1222,11 +1226,12 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N coordinates = [vector.get(reg) for reg in range(vaddr[0], vaddr[-1] + 1)] if not all(is_word(value) for value in coordinates): raise ValueError("Unverified image coordinates") - if a16: - packed = hlsl_word(coordinates[0]) - x, y = f"{packed} & 0xffffu", f"{packed} >> 16u" - else: - x, y = map(hlsl_word, coordinates[:2]) + if not resinfo: + if a16: + packed = hlsl_word(coordinates[0]) + x, y = f"{packed} & 0xffffu", f"{packed} >> 16u" + else: + x, y = map(hlsl_word, coordinates[:2]) if write: # A D3D12 Texture2D UAV names one mip. Verify native and desktop mip selection agree. level = coordinates[-1] if mip else 0 @@ -1243,14 +1248,22 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N texel = ", ".join(selected.get(channel, "0u") for channel in "xyzw") stores.append(f" outputData[uint2({x}, {y})] = uint4({texel});") continue - lod = "0" - if mip: - mip_word = hlsl_word(coordinates[-1]) - lod = f"asint({mip_word}{' & 0xffffu' if a16 else ''})" - address = f"int3(asint({x}), asint({y}), {lod})" - name = f"image_load_{image_step_count}" + if resinfo: + name = f"image_resinfo_{image_step_count}" + level = hlsl_word(coordinates[0]) + if a16: + level = f"({level} & 0xffffu)" + staged_steps.append((None, f" uint4 {name};\n" + f" imageData.GetDimensions({level}, {name}.x, {name}.y, {name}.w);")) + else: + lod = "0" + if mip: + mip_word = hlsl_word(coordinates[-1]) + lod = f"asint({mip_word}{' & 0xffffu' if a16 else ''})" + address = f"int3(asint({x}), asint({y}), {lod})" + name = f"image_load_{image_step_count}" + staged_steps.append((None, f" {IMAGE_FORMATS[image_format][0]} {name} = imageData.Load({address});")) image_step_count += 1 - staged_steps.append((None, f" {IMAGE_FORMATS[image_format][0]} {name} = imageData.Load({address});")) if m["packed"] and m["packed"].endswith("_sgn"): # The UINT SRV exposes raw bytes. Extend each byte from bit 7 to a full VGPR. staged_steps.append((None, f" {name} = asuint(asint({name} << 24u) >> 24u);")) From 2e8eebe32bdd162d782c3fa98675421299a4a18d Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:15:38 +0800 Subject: [PATCH 019/775] docs: record the ballot bit extraction readback on Intel Xe2 The ballot bit extraction section lists the RTX 4060 Laptop and WARP readbacks. Add the same measurement for the Intel Arc 140T at 0a679c06: 320 words with no mismatches, the exchange of positions 31 and 32 caught as exactly two mismatches, and all four faulty find-LSB lowerings caught, first at words 64, 32, 128 and 64 with 58, 115, 24 and 107 differing words. Zero debug errors and warnings in every run. Docs only. --- docs/experiments.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 2712f4d85..d41549d98 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7614,6 +7614,13 @@ independently of the desktop device's wave size. On RTX 4060 Laptop and WARP, bo readbacks matched 128 output words and 192 guards. Exchanging expected positions 31 and 32 produced exactly two mismatches on each adapter. +On Windows 11 build 26300.9974, the Intel Arc 140T (32.0.101.8132) matched the same +320 words with no mismatches, and exchanging expected positions 31 and 32 produced +exactly two mismatches, the first at word 31. The four faulty find-LSB lowerings were +each caught on this adapter too, first at words 64, 32, 128 and 64, with 58, 115, 24 +and 107 differing words, so the ballot results do not depend on this adapter's wave +width either. Every run reported zero D3D12 debug errors and warnings. + The same lowering handles `OpGroupNonUniformBallotFindLSB %uint %scope %ballot`, which SPIRV-Cross rejects for HLSL (the 2021.01.15 package stops with "Cannot trivially implement BallotFindLSB in HLSL"). Each of the four ballot words goes through GLSL `FindILsb`, offset by 0, 32, From 2dfe4df1c8506bf5f59e1653f9abf53f0f8a0b32 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:16:04 +0100 Subject: [PATCH 020/775] test: rename small to tiny_buf for MSVC rpcndr.h compatibility --- tests/startup_memory_srv_report_check.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/startup_memory_srv_report_check.cpp b/tests/startup_memory_srv_report_check.cpp index bc9241e23..d239af70b 100644 --- a/tests/startup_memory_srv_report_check.cpp +++ b/tests/startup_memory_srv_report_check.cpp @@ -85,11 +85,11 @@ int main() "res{unreadable} view{unreadable} dest=0x0 dest_in_view_heap=0 address=0x0 address_readable=0"); // A small buffer is cut, never overrun, and stays terminated. - char small[40]; - std::memset(small, 'x', sizeof(small)); - x2w_startup::report_refused_memory_srv(small, sizeof(small), "unsupported memory SRV arguments", "null_address", &bc7, + char tiny_buf[40]; + std::memset(tiny_buf, 'x', sizeof(tiny_buf)); + x2w_startup::report_refused_memory_srv(tiny_buf, sizeof(tiny_buf), "unsupported memory SRV arguments", "null_address", &bc7, &array, 0, false, 0x1000, true); - if (std::memchr(small, 0, sizeof(small)) == nullptr) { + if (std::memchr(tiny_buf, 0, sizeof(tiny_buf)) == nullptr) { ++failures; std::printf("FAIL truncated line is not terminated\n"); } From 82680176e9c417abb1ac57f3295aaa0a9a8c02ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 14:17:27 +0300 Subject: [PATCH 021/775] gpu: compare the placed DXR hit distance within 1e-5 of 1 dxr_placed_build and cpu_placed_dxr compared the hit distance bit for bit with 1.0f. An AMD Radeon RX 6600 returns 0x3f7fffff, one ULP below, so both hardware tests failed although the hit, instance, primitive and both misses were correct. check_dxr_rays, check_dxr_update and the facing checks already allow this with 1e-5 or 1e-4. Compare the distance within 1e-5 of 1 and every other word exactly. The guest-addressed scene must still equal the direct scene byte for byte. On a mismatch, dxr_placed_build now prints the 12 result words. --- docs/experiments.md | 11 ++++++++--- tests/cpu/placed_dxr_check.py | 14 +++++++++++++- tests/dxr_check.cpp | 18 ++++++++++++++++-- 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 2712f4d85..99a08d01b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6323,7 +6323,7 @@ ctest --preset release --no-tests=error --output-on-failure -R '^dxr_address_ran `dxr_placed_build_{hardware,warp}` creates four buffers through device slot 133. The BLAS and TLAS destinations start 512 bytes into their own buffers. Each build uses a separate UAV scratch buffer at offset 768. The internal desktop build preparation shares the vertex-binding placement lookup and checks the roles and byte ranges using the device's prebuild sizes. The destination is created in the acceleration-structure state. The fixture checks the offsets against the GPU addresses resolved at the allocation bases, records both builds, and calls `DispatchRays`. An unregistered destination, swapped buffer roles and a scratch extent one byte short of the TLAS requirement are rejected before command recording. The console build command encoding remains unverified. [Microsoft DXR memory requirements](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_build_raytracing_acceleration_structure_desc) -On Windows 11 build 26200.9974, the RTX 4060 Laptop (32.0.16.1656) required 2,304/1,920 result/scratch bytes for the BLAS and 2,048/2,176 bytes for the TLAS. WARP (10.0.26100.9818) required 100/120 and 168/212 respectively. Both returned all 12 expected ray result words for a hit at distance one, a spatial miss and a masked miss, with the debug layer enabled and zero errors or warnings. +On Windows 11 build 26200.9974, the RTX 4060 Laptop (32.0.16.1656) required 2,304/1,920 result/scratch bytes for the BLAS and 2,048/2,176 bytes for the TLAS. WARP (10.0.26100.9818) required 100/120 and 168/212 respectively. Both returned all 12 expected ray result words for a hit at distance one, a spatial miss and a masked miss, with the debug layer enabled and zero errors or warnings. The check compares the hit distance within 1e-5 of 1, as `dxr_query_*` and `dxr_pipeline_*` do, and the other 11 words exactly: at `153bb5f6` on Windows 11 build 26300.9974, an AMD Radeon RX 6600 (driver 32.0.21045.29003, 720/300 and 1,424/860 bytes) returned distance `0x3f7fffff`, one ULP below 1, with the other 11 words as expected, debug layer enabled and zero errors or warnings, in 3 of 3 runs. Before the tolerance, that distance failed the test. ```powershell cmake --build --preset release --target offscreen_check @@ -8552,8 +8552,13 @@ The Windows loader and `pe_map` run the same PE. The test checks that PE's hash against the compiled AOT executable's exported source hash. For every runner the successful batch builds one triangle and one instance, dispatches three rays, and reads 12 DWORDs. A separately built scene on the same device uses -direct desktop addresses. Both must yield instance 7 at distance 1, a miss and -a mask-filtered miss. The successful guest exits with 42. +direct desktop addresses. The direct scene must yield instance 7 at a distance +within 1e-5 of 1, a miss and a mask-filtered miss; every word but the distance +must match exactly. The guest-addressed scene must equal the direct scene byte +for byte, distance included. The successful guest exits with 42. At `153bb5f6` +on Windows 11 build 26300.9974, both scenes on an AMD Radeon RX 6600 (driver +32.0.21045.29003) returned distance `0x3f7fffff`, one ULP below 1, and the test +passed in 3 of 3 runs on that adapter and on WARP 10.0.26100.9818. Two controls change the second scratch address. One selects a resource whose last required byte falls beyond its registered extent. The other supplies an diff --git a/tests/cpu/placed_dxr_check.py b/tests/cpu/placed_dxr_check.py index 7efcfd9c1..2406b2596 100644 --- a/tests/cpu/placed_dxr_check.py +++ b/tests/cpu/placed_dxr_check.py @@ -11,6 +11,18 @@ from shim_compute_check import check_lifted_image +def check_ray_control(actual, expected): + """Every word but the hit distance must match exactly. As in check_dxr_rays, the distance (word 3) + must be within 1e-5 of 1, because hardware intersection may round it (the RX 6600 returns 0x3f7fffff).""" + if len(actual) != len(expected): + check("direct Windows ray control", actual, expected) + distance = struct.unpack_from(" expected{1,7,0,0x3f800000, 0,0,0,0, 0,0,0,0}; - if (output != expected) throw std::runtime_error("Placed BLAS/TLAS ray output differs from hit7@1, miss, masked miss"); - std::puts("Slot 133 placed BLAS/TLAS: hit7@1, miss, masked miss; 12/12 words matched"); + // Word 3 is the hit distance. As in check_dxr_rays, it must be within 1e-5 of 1, because hardware + // intersection may round it (the RX 6600 returns 0x3f7fffff). Every other word must match exactly. + float distance = 0; + if (output.size() == expected.size()) std::memcpy(&distance, &output[3], sizeof(distance)); + const bool matches = output.size() == expected.size() && + std::equal(output.begin(), output.begin() + 3, expected.begin()) && + std::equal(output.begin() + 4, output.end(), expected.begin() + 4) && + std::abs(distance - 1.f) < 1e-5f; + if (!matches) { + std::fprintf(stderr, "placed ray words:"); + for (const auto word : output) std::fprintf(stderr, " %08x", word); + std::fputc('\n', stderr); + throw std::runtime_error("Placed BLAS/TLAS ray output differs from hit7@1, miss, masked miss"); + } + std::printf("Slot 133 placed BLAS/TLAS: hit7@1 (distance=0x%08x), miss, masked miss; 11/11 words and the " + "distance matched\n", output[3]); return true; } From 22961a53ecd8bb3d5823b9c4ec7b2ad18b586fd2 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:19:24 +0800 Subject: [PATCH 022/775] docs: record the address-window and atomic readbacks on Intel Xe2 The SPIR-V address-window section lists the GTX 1060 and both WARP builds. Add the Intel Arc 140T at 0a679c06: all 128 words across the eight address-window cases and all 64 words across the four atomic cases matched, with zero D3D12 debug errors and warnings. Docs only. --- docs/experiments.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 82c8b5706..1345f834a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -780,6 +780,14 @@ Debug and Release with zero D3D12 warnings and errors. The original `cs_6_6` fixture skipped on both in-box adapters and passed the same cases on app-local WARP. +On Windows 11 build 26300.9974, the Intel Arc 140T (32.0.101.8132) matched all 128 +words across the same eight cases and all 64 words across the four atomic cases, +with zero D3D12 debug errors and warnings. The eight are the baseline, a swapped +pair, a moved output, a high address, an unaligned read, an index addition that +wraps, an unaligned write and a write beyond the descriptor; the atomic cases cover +a valid word, a misaligned one, one outside the window and a wrapping index +addition. + The SPIR-V bridge GPU tests (`spirv_{address_window,sampler_views,ballot_extract,compaction,compare_sampler}_{hardware,warp}`) need `spirv-as`, `spirv-val` and `spirv-cross`. `tools/setup-spirv-tools.ps1` builds them from pinned SPIRV-Tools, SPIRV-Headers and SPIRV-Cross revisions into `out/tools/spirv/bin`, where CMake looks From 4e69fd96f9785e9f249f6fb55a646e49e1706d65 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:20:49 +0100 Subject: [PATCH 023/775] runtime/inflate: return structured InflateStatus via inflate_zlib_ex --- CMakeLists.txt | 4 + docs/startup-runtime.md | 4 +- src/startup_stubs/inflate.h | 63 ++++++--- tests/startup_inflate_status.cpp | 216 +++++++++++++++++++++++++++++++ 4 files changed, 271 insertions(+), 16 deletions(-) create mode 100644 tests/startup_inflate_status.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6afbef55b..89d49c266 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -333,6 +333,10 @@ add_executable(startup_storage_file_range tests/startup_storage_file_range.cpp) target_compile_features(startup_storage_file_range PRIVATE cxx_std_17) target_include_directories(startup_storage_file_range PRIVATE src) add_test(NAME startup_storage_file_range COMMAND startup_storage_file_range) +add_executable(startup_inflate_status tests/startup_inflate_status.cpp) +target_compile_features(startup_inflate_status PRIVATE cxx_std_17) +target_include_directories(startup_inflate_status PRIVATE src) +add_test(NAME startup_inflate_status COMMAND startup_inflate_status) target_compile_features(startup_stub_consumer PRIVATE cxx_std_17) target_link_libraries(startup_stub_consumer PRIVATE startup_stub_chad startup_stub_xg_xs xmem_shim d3d12_xs_shim) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 75ef1d4b9..e6a4b7fdb 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -188,7 +188,9 @@ ctest --preset release --no-tests=error -R '^startup_launch$' -V ## zlib decoder check `tests/startup_inflate_check.py` (ctest `startup_inflate`) runs the DirectStorage stand-in's decoder -(`src/startup_stubs/inflate.h`) through the source-built `tests/startup_inflate_probe.cpp`. CPython's +(`src/startup_stubs/inflate.h`) through the source-built `tests/startup_inflate_probe.cpp`, and +`startup_inflate_status` (`tests/startup_inflate_status.cpp`) verifies `InflateStatus` classification +in `inflate_zlib_ex` (`ok`, `insufficient_output`, `corrupt_stream`, `bad_checksum`). CPython's zlib encodes seeded synthetic data as stored, fixed and dynamic Huffman blocks, with matches up to the 32 KiB window and a sync flush between blocks; each result must equal the input. A stream with one byte too little capacity and a truncated stream must be rejected without writes past the diff --git a/src/startup_stubs/inflate.h b/src/startup_stubs/inflate.h index 8d3841169..a43302c35 100644 --- a/src/startup_stubs/inflate.h +++ b/src/startup_stubs/inflate.h @@ -18,6 +18,7 @@ struct Stream { std::uint32_t bit_buffer = 0; int bit_count = 0; bool failed = false; + bool overflow = false; }; inline std::uint32_t bits(Stream& s, int need) noexcept @@ -90,7 +91,10 @@ inline bool codes(Stream& s, const Huffman& lencode, const Huffman& distcode) no int symbol = decode(s, lencode); if (symbol < 0) return false; if (symbol < 256) { - if (s.out_pos == s.out_size) return false; + if (s.out_pos == s.out_size) { + s.overflow = true; + return false; + } s.out[s.out_pos++] = static_cast(symbol); } else if (symbol == 256) { return true; @@ -101,7 +105,11 @@ inline bool codes(Stream& s, const Huffman& lencode, const Huffman& distcode) no symbol = decode(s, distcode); if (symbol < 0 || symbol >= 30) return false; const std::size_t distance = dist_base[symbol] + bits(s, dist_extra[symbol]); - if (s.failed || distance > s.out_pos || length > s.out_size - s.out_pos) return false; + if (s.failed || distance > s.out_pos) return false; + if (length > s.out_size - s.out_pos) { + s.overflow = true; + return false; + } for (std::size_t i = 0; i < length; ++i, ++s.out_pos) s.out[s.out_pos] = s.out[s.out_pos - distance]; } } @@ -115,7 +123,11 @@ inline bool stored(Stream& s) noexcept const unsigned length = s.in[s.in_pos] | (s.in[s.in_pos + 1] << 8); const unsigned check = s.in[s.in_pos + 2] | (s.in[s.in_pos + 3] << 8); s.in_pos += 4; - if ((length ^ check) != 0xFFFF || length > s.in_size - s.in_pos || length > s.out_size - s.out_pos) return false; + if ((length ^ check) != 0xFFFF || length > s.in_size - s.in_pos) return false; + if (length > s.out_size - s.out_pos) { + s.overflow = true; + return false; + } for (unsigned i = 0; i < length; ++i) s.out[s.out_pos++] = s.in[s.in_pos++]; return true; } @@ -208,22 +220,43 @@ inline std::uint32_t adler32(const unsigned char* data, std::size_t size) noexce return (b << 16) | a; } -// zlib stream (2-byte header, deflate data, Adler-32). The checksum must match. -inline bool inflate_zlib(const unsigned char* in, std::size_t in_size, unsigned char* out, std::size_t out_size, - std::size_t* produced) noexcept +enum class InflateStatus { + ok, + insufficient_output, + corrupt_stream, + bad_checksum, +}; + +// zlib stream (2-byte header, deflate data, Adler-32). Distinguishes output capacity overflow +// and Adler-32 mismatch from corrupt headers/deflate data. +inline InflateStatus inflate_zlib_ex(const std::uint8_t* input, std::size_t input_size, std::uint8_t* output, + std::size_t capacity, std::size_t& out_size) noexcept { - if (produced) *produced = 0; - if (in_size < 6 || (in[0] & 0x0F) != 8 || ((in[0] << 8) | in[1]) % 31 != 0 || (in[1] & 0x20)) return false; - Stream s{in + 2, in_size - 2}; - s.out = out; - s.out_size = out_size; - if (!inflate_raw(s)) return false; - if (produced) *produced = s.out_pos; - if (s.in_size - s.in_pos < 4) return false; + out_size = 0; + if (!input || (!output && capacity > 0) || input_size < 6 || (input[0] & 0x0F) != 8 || + ((input[0] << 8) | input[1]) % 31 != 0 || (input[1] & 0x20)) { + return InflateStatus::corrupt_stream; + } + Stream s{input + 2, input_size - 2, 0, output, capacity}; + if (!inflate_raw(s)) { + return s.overflow ? InflateStatus::insufficient_output : InflateStatus::corrupt_stream; + } + out_size = s.out_pos; + if (s.in_size - s.in_pos < 4) return InflateStatus::corrupt_stream; const unsigned char* tail = s.in + s.in_pos; const std::uint32_t expected = (std::uint32_t{tail[0]} << 24) | (std::uint32_t{tail[1]} << 16) | (std::uint32_t{tail[2]} << 8) | tail[3]; - return adler32(out, s.out_pos) == expected; + return adler32(output, s.out_pos) == expected ? InflateStatus::ok : InflateStatus::bad_checksum; +} + +// zlib stream (2-byte header, deflate data, Adler-32). The checksum must match. +inline bool inflate_zlib(const unsigned char* in, std::size_t in_size, unsigned char* out, std::size_t out_size, + std::size_t* produced) noexcept +{ + std::size_t out_size_tmp = 0; + const InflateStatus status = inflate_zlib_ex(in, in_size, out, out_size, out_size_tmp); + if (produced) *produced = out_size_tmp; + return status == InflateStatus::ok; } } // namespace x2w_inflate diff --git a/tests/startup_inflate_status.cpp b/tests/startup_inflate_status.cpp new file mode 100644 index 000000000..bf807e5b7 --- /dev/null +++ b/tests/startup_inflate_status.cpp @@ -0,0 +1,216 @@ +#include "startup_stubs/inflate.h" + +#include +#include +#include +#include +#include + +namespace { + +using x2w_inflate::InflateStatus; +using x2w_inflate::inflate_zlib; +using x2w_inflate::inflate_zlib_ex; + +bool check_ok(const char* name, const std::uint8_t* stream, std::size_t stream_size, + const std::uint8_t* expected, std::size_t expected_size) +{ + std::vector out(expected_size, 0xAA); + std::size_t out_size = 999; + const InflateStatus status = inflate_zlib_ex(stream, stream_size, out.data(), out.size(), out_size); + if (status != InflateStatus::ok || out_size != expected_size || + std::memcmp(out.data(), expected, expected_size) != 0) { + std::fprintf(stderr, "%s: expected ok/%zu, got status=%d out_size=%zu\n", name, expected_size, + static_cast(status), out_size); + return false; + } + std::vector compat_out(expected_size, 0x55); + std::size_t compat_size = 0; + if (!inflate_zlib(stream, stream_size, compat_out.data(), compat_out.size(), &compat_size) || + compat_size != expected_size || std::memcmp(compat_out.data(), expected, expected_size) != 0) { + std::fprintf(stderr, "%s: inflate_zlib wrapper mismatch\n", name); + return false; + } + return true; +} + +bool check_insufficient(const char* name, const std::uint8_t* stream, std::size_t stream_size, std::size_t capacity) +{ + std::vector out(capacity + 1, 0xCC); + std::size_t out_size = 999; + const InflateStatus status = inflate_zlib_ex(stream, stream_size, out.data(), capacity, out_size); + if (status != InflateStatus::insufficient_output || status == InflateStatus::corrupt_stream || + status == InflateStatus::bad_checksum) { + std::fprintf(stderr, "%s: expected insufficient_output, got status=%d\n", name, static_cast(status)); + return false; + } + if (out[capacity] != 0xCC) { + std::fprintf(stderr, "%s: wrote past capacity=%zu\n", name, capacity); + return false; + } + std::size_t compat_size = 999; + if (inflate_zlib(stream, stream_size, out.data(), capacity, &compat_size) || compat_size != 0) { + std::fprintf(stderr, "%s: inflate_zlib wrapper should return false with produced=0\n", name); + return false; + } + return true; +} + +bool check_status(const char* name, const std::uint8_t* stream, std::size_t stream_size, std::size_t capacity, + InflateStatus expected_status) +{ + std::vector out(capacity, 0xDD); + std::size_t out_size = 999; + const InflateStatus status = inflate_zlib_ex(stream, stream_size, out.data(), capacity, out_size); + if (status != expected_status) { + std::fprintf(stderr, "%s: expected status=%d, got status=%d\n", name, static_cast(expected_status), + static_cast(status)); + return false; + } + std::size_t compat_size = 999; + if (inflate_zlib(stream, stream_size, out.data(), capacity, &compat_size)) { + std::fprintf(stderr, "%s: inflate_zlib wrapper unexpectedly succeeded\n", name); + return false; + } + return true; +} + +std::vector dynamic_payload() +{ + std::uint32_t x = 0x12345678u; + auto next_u8 = [&x](std::uint32_t mod) -> std::uint8_t { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + return static_cast((x >> 16) % mod); + }; + std::vector data; + data.reserve(600); + for (int i = 0; i < 300; ++i) data.push_back(next_u8(256)); + for (int i = 0; i < 300; ++i) data.push_back(next_u8(32)); + return data; +} + +} // namespace + +int main() +{ + // 1. Stored block: "Hello, stored!" (14 bytes) + static const std::uint8_t stored_stream[] = { + 0x78, 0x01, 0x01, 0x0e, 0x00, 0xf1, 0xff, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, + 0x20, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x64, 0x21, 0x25, 0x9d, 0x04, 0xf3, + }; + static const std::uint8_t stored_expected[] = {'H', 'e', 'l', 'l', 'o', ',', ' ', + 's', 't', 'o', 'r', 'e', 'd', '!'}; + + // 2. Fixed Huffman literals only: "abcdefghij" (10 bytes) + static const std::uint8_t fixed_lit_stream[] = { + 0x78, 0x9c, 0x4b, 0x4c, 0x4a, 0x4e, 0x49, 0x4d, 0x4b, 0xcf, 0xc8, 0xcc, 0x02, 0x00, 0x15, 0x86, 0x03, 0xf8, + }; + static const std::uint8_t fixed_lit_expected[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}; + + // 3. Fixed Huffman with LZ77 back-reference match-copy: "ABCD" * 5 (20 bytes) + static const std::uint8_t fixed_match_stream[] = { + 0x78, 0x9c, 0x73, 0x74, 0x72, 0x76, 0x71, 0x44, 0xc3, 0x00, 0x36, 0x88, 0x05, 0x33, + }; + static const std::uint8_t fixed_match_expected[] = { + 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', + }; + + // 4. Dynamic Huffman (BTYPE=2) with literals + matches (600 bytes) + static const std::uint8_t dynamic_stream[] = { + 0x78, 0x9c, 0x05, 0xc1, 0x59, 0x48, 0x14, 0x61, 0x00, 0x00, 0xe0, 0x99, 0xf9, 0x67, 0x67, 0xe7, 0x9f, 0x7b, + 0xfe, 0xd9, 0x39, 0xff, 0x9d, 0x19, 0xf5, 0xc1, 0xf2, 0xc1, 0x15, 0xa9, 0x87, 0x50, 0x84, 0x12, 0x12, 0x2a, + 0x43, 0x45, 0x8d, 0xca, 0xd2, 0x24, 0xa4, 0x03, 0x31, 0x37, 0xa8, 0x14, 0x3a, 0xd0, 0x68, 0x13, 0x71, 0x0b, + 0xc3, 0x0d, 0x59, 0x31, 0xc5, 0x88, 0x2c, 0xec, 0x61, 0xe9, 0xd2, 0x2e, 0xc9, 0xa2, 0x40, 0x93, 0xa2, 0x12, + 0xca, 0x30, 0x03, 0x45, 0x02, 0xb3, 0xa8, 0x07, 0xa1, 0xcb, 0xfa, 0xbe, 0xee, 0xaa, 0xb4, 0x9b, 0x79, 0x83, + 0xe3, 0x56, 0x53, 0x6a, 0x54, 0x7e, 0x54, 0xf7, 0x6c, 0xba, 0x23, 0x39, 0xf6, 0xb4, 0x62, 0xee, 0xf7, 0x96, + 0xc4, 0x70, 0x84, 0x3e, 0xb7, 0xf4, 0x1a, 0xbc, 0xfd, 0xd4, 0x7a, 0xb4, 0xbb, 0xb0, 0x72, 0x4f, 0xdd, 0x97, + 0xfa, 0xdc, 0x87, 0x77, 0x9b, 0x27, 0x5e, 0x95, 0xaf, 0x38, 0xbd, 0xbc, 0x25, 0x64, 0xa1, 0x8e, 0xae, 0x44, + 0xbc, 0x43, 0x59, 0xe9, 0x9d, 0x4c, 0x3f, 0x1d, 0x49, 0x0e, 0x6c, 0x6a, 0x8c, 0xe3, 0x8c, 0xd8, 0xa1, 0xf9, + 0xe4, 0x42, 0x97, 0x5a, 0x53, 0x50, 0x50, 0x54, 0xd8, 0x5c, 0x3d, 0xd6, 0x59, 0x1f, 0x5a, 0x77, 0xc9, 0x58, + 0xdc, 0xd9, 0xc8, 0xcd, 0xb6, 0x5d, 0x8e, 0x46, 0xc6, 0x67, 0xef, 0xb4, 0x5f, 0xcf, 0x29, 0x5e, 0x6c, 0x2f, + 0x3f, 0x58, 0xda, 0xb6, 0x18, 0x9b, 0xe8, 0xad, 0xad, 0xc8, 0xfe, 0x43, 0x17, 0xb4, 0xef, 0xd8, 0xb6, 0x94, + 0x16, 0xdd, 0xee, 0xf6, 0x35, 0xdd, 0xfa, 0x71, 0xf8, 0xeb, 0x89, 0x51, 0x73, 0xff, 0x42, 0xf5, 0x15, 0x60, + 0x70, 0xd1, 0x37, 0x5b, 0x07, 0xfd, 0x0b, 0x33, 0x19, 0x5e, 0x69, 0xff, 0xc0, 0xa9, 0xe5, 0x93, 0xd7, 0xb2, + 0xbf, 0x9d, 0x99, 0x2c, 0x23, 0x72, 0x53, 0xcb, 0x0b, 0x71, 0xb5, 0x27, 0xbf, 0x65, 0x6a, 0xe6, 0x6f, 0xce, + 0x78, 0xe7, 0xcb, 0x7d, 0xb3, 0x53, 0xb1, 0xdb, 0xd5, 0x59, 0x1f, 0x22, 0xa9, 0xcf, 0xc1, 0x86, 0xb2, 0xcc, + 0x44, 0x51, 0xc3, 0x8d, 0xf4, 0x5f, 0x13, 0xf9, 0xff, 0x76, 0xbd, 0x58, 0x4d, 0xb7, 0xe4, 0x7d, 0xbf, 0xd8, + 0x37, 0x42, 0xac, 0xf1, 0xdf, 0xf5, 0x93, 0x3f, 0x8b, 0x9f, 0xaf, 0xad, 0x39, 0x8f, 0x9f, 0xf4, 0xcc, 0xc7, + 0x36, 0x9b, 0x8f, 0x87, 0xf2, 0xa7, 0x93, 0xe2, 0xbd, 0xd6, 0xb9, 0x92, 0xb3, 0x95, 0x9d, 0x23, 0xef, 0xe3, + 0x8d, 0x99, 0xe2, 0x4c, 0x74, 0xe3, 0xd0, 0xfa, 0xf9, 0x23, 0xbb, 0x0f, 0xdc, 0xcf, 0x8e, 0x36, 0x0c, 0x84, + 0x3f, 0x6a, 0xc5, 0xe2, 0xb1, 0x07, 0xab, 0x86, 0xab, 0xc8, 0xda, 0xba, 0xbd, 0x25, 0x99, 0xc2, 0xd5, 0xe3, + 0x09, 0x71, 0x83, 0x4a, 0x03, 0x27, 0xa4, 0xb2, 0x98, 0x91, 0x14, 0x46, 0xd4, 0x78, 0x9b, 0x17, 0xa0, 0xc1, + 0x4b, 0x96, 0xa8, 0x39, 0x01, 0xc9, 0x53, 0x5c, 0x57, 0xf3, 0x29, 0xdf, 0xb1, 0x0c, 0xc8, 0x5b, 0x34, 0x70, + 0x81, 0x4c, 0x41, 0xe0, 0xd8, 0xa6, 0x42, 0x43, 0x59, 0xe5, 0xc4, 0xa0, 0x83, 0xc3, 0xa6, 0xad, 0x31, 0x2e, + 0xf0, 0x20, 0x19, 0x74, 0x49, 0x20, 0xf1, 0x0e, 0xf4, 0x6c, 0x91, 0x50, 0x11, 0x21, 0x08, 0x04, 0x03, 0x7c, + 0x6c, 0xd1, 0x90, 0xe3, 0x6c, 0x43, 0x61, 0x15, 0x48, 0xb0, 0x61, 0x85, 0x32, 0x91, 0x0b, 0x18, 0xd6, 0xf3, + 0x15, 0x9e, 0x60, 0x42, 0x2e, 0x8b, 0x25, 0x86, 0xa5, 0x34, 0x43, 0xa1, 0xe5, 0xa0, 0xc3, 0xbb, 0x84, 0xed, + 0x59, 0x41, 0x45, 0xc0, 0x2a, 0x94, 0x48, 0x46, 0x17, 0x80, 0xea, 0x03, 0x99, 0x44, 0x80, 0x66, 0xa0, 0x8d, + 0x11, 0x1f, 0x60, 0x38, 0x0a, 0xdb, 0x1c, 0xa5, 0xa9, 0xa6, 0xee, 0xf9, 0x3a, 0x11, 0xb6, 0x15, 0x33, 0xa0, + 0x68, 0xa4, 0x48, 0x51, 0x4e, 0xd0, 0x62, 0x05, 0x42, 0xb2, 0x25, 0x3b, 0x64, 0x22, 0x96, 0x42, 0x28, 0xa4, + 0x63, 0xd1, 0xc5, 0x72, 0x40, 0x63, 0x45, 0x5a, 0x34, 0x81, 0x29, 0x5b, 0x80, 0x84, 0x14, 0xd2, 0x64, 0xec, + 0x7b, 0x3a, 0x44, 0xc8, 0xf0, 0x14, 0x03, 0x79, 0x96, 0x28, 0xcb, 0x3a, 0x16, 0x4c, 0xdb, 0x45, 0x94, 0x6e, + 0x22, 0xce, 0x61, 0x05, 0x13, 0x07, 0x0c, 0xd5, 0x16, 0x5d, 0x08, 0x69, 0x95, 0x0f, 0xf3, 0x2c, 0x70, 0x61, + 0x98, 0x50, 0xb0, 0xce, 0x91, 0x1a, 0x45, 0xfd, 0x07, 0x3f, 0x85, 0xa3, 0x6c, + }; + const std::vector dyn_expected = dynamic_payload(); + + bool ok = true; + + // Exact-size buffer -> ok + ok = ok && check_ok("stored", stored_stream, sizeof(stored_stream), stored_expected, sizeof(stored_expected)); + ok = ok && check_ok("fixed_lit", fixed_lit_stream, sizeof(fixed_lit_stream), fixed_lit_expected, + sizeof(fixed_lit_expected)); + ok = ok && check_ok("fixed_match", fixed_match_stream, sizeof(fixed_match_stream), fixed_match_expected, + sizeof(fixed_match_expected)); + ok = ok && check_ok("dynamic", dynamic_stream, sizeof(dynamic_stream), dyn_expected.data(), dyn_expected.size()); + + // capacity == exact - 1 across stored, literal emit, match-copy, and dynamic -> insufficient_output + ok = ok && check_insufficient("stored_short", stored_stream, sizeof(stored_stream), sizeof(stored_expected) - 1); + ok = ok && check_insufficient("fixed_lit_short", fixed_lit_stream, sizeof(fixed_lit_stream), + sizeof(fixed_lit_expected) - 1); + ok = ok && check_insufficient("fixed_match_short", fixed_match_stream, sizeof(fixed_match_stream), + sizeof(fixed_match_expected) - 1); + ok = ok && check_insufficient("dynamic_short", dynamic_stream, sizeof(dynamic_stream), dyn_expected.size() - 1); + + // Corrupted Adler-32 trailer -> bad_checksum + std::vector bad_adler(fixed_match_stream, fixed_match_stream + sizeof(fixed_match_stream)); + bad_adler.back() ^= 0x01; + ok = ok && check_status("bad_adler32", bad_adler.data(), bad_adler.size(), sizeof(fixed_match_expected), + InflateStatus::bad_checksum); + + // Invalid zlib headers -> corrupt_stream + static const std::uint8_t bad_cmf[] = {0x79, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01}; + static const std::uint8_t bad_fcheck[] = {0x78, 0x9d, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01}; + static const std::uint8_t fdict_set[] = {0x78, 0xbb, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01}; + static const std::uint8_t too_short[] = {0x78, 0x9c, 0x03, 0x00, 0x00}; + ok = ok && check_status("bad_cmf", bad_cmf, sizeof(bad_cmf), 16, InflateStatus::corrupt_stream); + ok = ok && check_status("bad_fcheck", bad_fcheck, sizeof(bad_fcheck), 16, InflateStatus::corrupt_stream); + ok = ok && check_status("fdict_set", fdict_set, sizeof(fdict_set), 16, InflateStatus::corrupt_stream); + ok = ok && check_status("too_short", too_short, sizeof(too_short), 16, InflateStatus::corrupt_stream); + + // Truncated stream (missing trailer and truncated deflate) -> corrupt_stream + ok = ok && check_status("truncated_trailer", fixed_lit_stream, sizeof(fixed_lit_stream) - 1, + sizeof(fixed_lit_expected), InflateStatus::corrupt_stream); + ok = ok && check_status("truncated_deflate", fixed_lit_stream, sizeof(fixed_lit_stream) - 6, + sizeof(fixed_lit_expected), InflateStatus::corrupt_stream); + + // Invalid block type (BTYPE=11: bits 1, 1, 1 -> 0x07) -> corrupt_stream + static const std::uint8_t bad_btype[] = {0x78, 0x9c, 0x07, 0x00, 0x00, 0x00, 0x00, 0x01}; + ok = ok && check_status("bad_btype", bad_btype, sizeof(bad_btype), 16, InflateStatus::corrupt_stream); + + // Invalid dynamic Huffman header (hlit=31 -> nlen=288 > 286) -> corrupt_stream + // bits: bfinal=1(1), btype=10(2), hlit=31(5) -> 0b11111_10_1 = 0xFD + static const std::uint8_t bad_dyn_huffman[] = {0x78, 0x9c, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x01}; + ok = ok && check_status("bad_dyn_huffman", bad_dyn_huffman, sizeof(bad_dyn_huffman), 16, + InflateStatus::corrupt_stream); + + // Out-of-window back-reference in fixed Huffman (bfinal=1, btype=01, len=257(3), dist=0(1), eob=256) + // Deflate Huffman codes are MSB-first: 257 = 0000001, dist 0 = 00000, 256 = 0000000 -> 0x03, 0x02, 0x00 + static const std::uint8_t bad_backref[] = {0x78, 0x9c, 0x03, 0x02, 0x00, 0x00, 0x00, 0x00, 0x01}; + ok = ok && check_status("bad_backref_roomy", bad_backref, sizeof(bad_backref), 16, InflateStatus::corrupt_stream); + ok = ok && check_status("bad_backref_zero_cap", bad_backref, sizeof(bad_backref), 0, InflateStatus::corrupt_stream); + + return ok ? 0 : 1; +} From ff03ffc41acf7ece0aa0ad31285b45af7268e637 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:22:32 +0100 Subject: [PATCH 024/775] d3d12_xs: wire slot 50 DSV binding, view_slot<21> tracking, and stream PSO depth-stencil subobjects --- CMakeLists.txt | 8 + src/startup_stubs/d3d12_capture.inl | 12 +- src/startup_stubs/d3d12_draw.inl | 36 +++- src/startup_stubs/d3d12_xs_device.cpp | 75 +++++-- tests/startup_stream_depth.cpp | 298 ++++++++++++++++++++++++++ tests/startup_stream_depth_check.py | 72 +++++++ 6 files changed, 475 insertions(+), 26 deletions(-) create mode 100644 tests/startup_stream_depth.cpp create mode 100644 tests/startup_stream_depth_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6afbef55b..a1747ee81 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -453,6 +453,10 @@ add_executable(startup_stream_consumer tests/startup_stream_consumer.cpp tests/s target_compile_features(startup_stream_consumer PRIVATE cxx_std_17) target_link_libraries(startup_stream_consumer PRIVATE d3d12_xs_shim startup_stub_xg_xs d3d12 dxgi) +add_executable(startup_stream_depth tests/startup_stream_depth.cpp tests/startup_stream_setup.cpp) +target_compile_features(startup_stream_depth PRIVATE cxx_std_17) +target_link_libraries(startup_stream_depth PRIVATE d3d12_xs_shim d3d12 dxgi) + # Console queue Wait (slot 17) waits on the GPU instead of signalling the fence. add_executable(startup_queue_wait tests/startup_queue_wait.cpp) target_compile_features(startup_queue_wait PRIVATE cxx_std_17) @@ -1415,6 +1419,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_draw_check.py" "$" "${backend}") set_tests_properties(startup_stream_draw_${backend} PROPERTIES TIMEOUT 90) + add_test(NAME startup_stream_depth_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_depth_check.py" + "$" "${backend}") + set_tests_properties(startup_stream_depth_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) foreach(compiler IN ITEMS fxc dxc) add_test(NAME startup_mrt_${compiler}_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mrt_check.py" diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index f2adce19f..383600e66 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -13,6 +13,9 @@ struct PipelineInfo { Translation* stream_translation = nullptr; bool has_stream_blend = false; D3D12_BLEND_DESC stream_blend{}; + bool has_stream_depth_stencil = false; + D3D12_DEPTH_STENCIL_DESC stream_depth_stencil{}; + DXGI_FORMAT stream_dsv_format = DXGI_FORMAT_UNKNOWN; int path = 0; // creating device slot: 57, 67, 55, 86, 62 Wrapper* base = nullptr; // slot 55: the pipeline it derives from std::vector desc; @@ -88,7 +91,9 @@ bool title_backed(u64 title_handle, u64 bytes) } void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std::size_t bytes, - Translation* translation = nullptr, const D3D12_BLEND_DESC* blend = nullptr) + Translation* translation = nullptr, const D3D12_BLEND_DESC* blend = nullptr, + const D3D12_DEPTH_STENCIL_DESC* depth_stencil = nullptr, + DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN) { PipelineInfo info; info.stream_translation = translation; @@ -96,6 +101,11 @@ void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std info.stream_blend = *blend; info.has_stream_blend = true; } + if (depth_stencil) { + info.stream_depth_stencil = *depth_stencil; + info.has_stream_depth_stencil = true; + } + info.stream_dsv_format = dsv_format; info.path = path; info.base = as_wrapper(base); const std::size_t have = desc ? readable_window(reinterpret_cast(desc), bytes) : 0; diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 157a3a388..80fa117d8 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -31,6 +31,9 @@ struct BoundPipeline { Translation* translation = nullptr; bool has_blend = false; D3D12_BLEND_DESC blend{}; + bool has_depth_stencil = false; + D3D12_DEPTH_STENCIL_DESC depth_stencil{}; + DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; std::unordered_map pipelines; // by target formats }; @@ -212,7 +215,8 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* } // Resolve the shader pointers and wrapped root while the caller still owns the stream. -Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3D12_BLEND_DESC& blend, bool& has_blend) +Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3D12_BLEND_DESC& blend, bool& has_blend, + D3D12_DEPTH_STENCIL_DESC& depth_stencil, bool& has_depth_stencil, DXGI_FORMAT& dsv_format) { const auto* stream = static_cast(desc.pPipelineStateSubobjectStream); if (!desc.SizeInBytes || desc.SizeInBytes > 0x2000 || desc.SizeInBytes % 8 || @@ -241,6 +245,13 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 } else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) { std::memcpy(&blend, stream + at + sizeof(type), sizeof(blend)); has_blend = true; + } else if (type == 11 || type == 21) { // DEPTH_STENCIL (56B) / DEPTH_STENCIL1 (64B) + std::memcpy(&depth_stencil, stream + at + sizeof(type), sizeof(depth_stencil)); + has_depth_stencil = true; + } else if (type == 16) { // DEPTH_STENCIL_FORMAT (8B) + DXGI_FORMAT fmt = DXGI_FORMAT_UNKNOWN; + std::memcpy(&fmt, stream + at + sizeof(type), sizeof(fmt)); + dsv_format = desktop_format(fmt); } at += stream_sizes[type]; } @@ -314,7 +325,14 @@ BoundPipeline* translation_for(Wrapper* pipeline) } } } - if (info && info->path == 86) result = info->stream_translation; + if (info && info->path == 86) { + result = info->stream_translation; + if (info->has_stream_depth_stencil) { + bound->depth_stencil = info->stream_depth_stencil; + bound->has_depth_stencil = true; + } + bound->dsv_format = info->stream_dsv_format; + } if (info && info->path == 57 && info->desc.size() >= 0x60) { u64 words[12]; std::memcpy(words, info->desc.data(), sizeof(words)); @@ -389,20 +407,24 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass) { + const DXGI_FORMAT dsv_format = pass.dsv_format != DXGI_FORMAT_UNKNOWN ? pass.dsv_format : bound.dsv_format; u64 key = pass.target_count; for (UINT i = 0; i < pass.target_count; ++i) key = key * 131 + static_cast(pass.target_formats[i]); + key = fnv_bytes(&dsv_format, sizeof(dsv_format), key); + if (bound.has_depth_stencil) key = fnv_bytes(&bound.depth_stencil, sizeof(bound.depth_stencil), key); const auto found = bound.pipelines.find(key); if (found != bound.pipelines.end()) return found->second; D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; desc.pRootSignature = tr.root; desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()}; desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; - // Blend state as found in the pipeline's state block, else opaque. Raster and depth state are - // not decoded yet: no culling, no depth (enough for the 2D start-up screens). + // Blend state as found in the pipeline's state block, else opaque. Depth-stencil state and + // DSVFormat come from the stream PSO (or bound DSV), else disabled. Raster state: no culling. for (auto& target : desc.BlendState.RenderTarget) target = {FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; if (bound.has_blend) desc.BlendState = bound.blend; + if (bound.has_depth_stencil) desc.DepthStencilState = bound.depth_stencil; desc.SampleMask = ~0u; desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; @@ -410,11 +432,13 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; desc.NumRenderTargets = pass.target_count; for (UINT i = 0; i < pass.target_count; ++i) desc.RTVFormats[i] = pass.target_formats[i]; + desc.DSVFormat = dsv_format; desc.SampleDesc.Count = 1; ID3D12PipelineState* pipeline = nullptr; const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); - log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx", tr.key, pass.target_count, - pass.target_count ? pass.target_formats[0] : 0, static_cast(hr)); + log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d)", tr.key, + pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast(hr), + static_cast(dsv_format), desc.DepthStencilState.DepthEnable ? 1 : 0); check_device("translated CreateGraphicsPipelineState", 0); bound.pipelines[key] = pipeline; return pipeline; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index c9e9431f4..197feaedc 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1632,6 +1632,7 @@ struct Pass { PlacedVertexView placed_vb[8] = {}; D3D12_INDEX_BUFFER_VIEW ib = {}; DXGI_FORMAT target_formats[8] = {}; + DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; UINT target_count = 0; ID3D12Resource* target0 = nullptr; // desktop resource of render target 0 (for per-draw dumps) bool heap_set = false; @@ -1699,32 +1700,63 @@ void __stdcall list_graphics_root(Wrapper* self, void* root) if (auto* list = recording(self); list && w && w->own().kind == root_signature_kind && w->own().real) list->SetGraphicsRootSignature(static_cast(w->own().real)); } -// List slot 50 (desktop 46 + 4), OMSetRenderTargets(count, handles, single range, depth). Depth is not bound yet. -void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, BOOL single_range, const void*) +DXGI_FORMAT view_format_of(u64 desktop_handle, ID3D12Resource* target) +{ + DXGI_FORMAT format = target->GetDesc().Format; + if (const std::uint32_t id = shadow_id(desktop_handle)) { + AcquireSRWLockShared(¬e_lock); + DXGI_FORMAT view_format = DXGI_FORMAT_UNKNOWN; + if (id - 1 < view_records().size() && view_records()[id - 1].desc_bytes >= 4) + std::memcpy(&view_format, view_records()[id - 1].desc, 4); + ReleaseSRWLockShared(¬e_lock); + if (view_format != DXGI_FORMAT_UNKNOWN) format = desktop_format(view_format); + } + return format; +} +// List slot 50 (desktop 46 + 4), OMSetRenderTargets(count, handles, single range, depth). +void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, BOOL single_range, + const D3D12_CPU_DESCRIPTOR_HANDLE* depth) { auto* list = recording(self); Pass& pass = pass_of(self); pass.targets_bound = false; - if (!list || !count || count > 8 || single_range || !x2w_local::readable(handles, count * sizeof(*handles))) return; + pass.target_count = 0; + pass.target0 = nullptr; + pass.dsv_format = DXGI_FORMAT_UNKNOWN; + if (!list || count > 8 || single_range) return; + if (count && !x2w_local::readable(handles, count * sizeof(*handles))) return; D3D12_CPU_DESCRIPTOR_HANDLE desktop[8]; + ID3D12Resource* targets[8]{}; + DXGI_FORMAT formats[8]{}; for (UINT i = 0; i < count; ++i) { desktop[i].ptr = static_cast(desktop_cpu_handle(handles[i].ptr)); - ID3D12Resource* target = view_target(desktop[i].ptr); - if (!target) return; - use_as_target(self, target); - DXGI_FORMAT format = target->GetDesc().Format; - if (const std::uint32_t id = shadow_id(desktop[i].ptr)) { - AcquireSRWLockShared(¬e_lock); - DXGI_FORMAT view_format = DXGI_FORMAT_UNKNOWN; - if (id - 1 < view_records().size() && view_records()[id - 1].desc_bytes >= 4) std::memcpy(&view_format, view_records()[id - 1].desc, 4); - ReleaseSRWLockShared(¬e_lock); - if (view_format != DXGI_FORMAT_UNKNOWN) format = desktop_format(view_format); + targets[i] = view_target(desktop[i].ptr); + if (!targets[i]) return; + formats[i] = view_format_of(desktop[i].ptr, targets[i]); + } + D3D12_CPU_DESCRIPTOR_HANDLE desktop_dsv{}; + const D3D12_CPU_DESCRIPTOR_HANDLE* dsv_ptr = nullptr; + ID3D12Resource* dsv_target = nullptr; + DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; + if (depth && x2w_local::readable(depth, sizeof(*depth))) { + const u64 resolved = desktop_cpu_handle(depth->ptr); + dsv_target = resolved ? view_target(resolved) : nullptr; + if (dsv_target) { + desktop_dsv.ptr = static_cast(resolved); + dsv_ptr = &desktop_dsv; + dsv_format = view_format_of(resolved, dsv_target); } - pass.target_formats[i] = format; - if (i == 0) pass.target0 = target; } + if (!count && !dsv_ptr) return; + for (UINT i = 0; i < count; ++i) { + use_as_target(self, targets[i]); + pass.target_formats[i] = formats[i]; + if (i == 0) pass.target0 = targets[i]; + } + if (dsv_target) require_state(self, dsv_target, D3D12_RESOURCE_STATE_DEPTH_WRITE); pass.target_count = count; - list->OMSetRenderTargets(count, desktop, FALSE, nullptr); + pass.dsv_format = dsv_format; + list->OMSetRenderTargets(count, count ? desktop : nullptr, FALSE, dsv_ptr); pass.targets_bound = true; } // List slots 21 / 22 / 23, RSSetViewports / RSSetScissorRects / OMSetBlendFactor. @@ -2210,7 +2242,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) args[1] = reinterpret_cast(&null_rtv); } const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); - if (N == 20 && args[0]) note_view_target(args[D], reinterpret_cast(args[0])); + if ((N == 20 || N == 21) && args[0]) note_view_target(args[D], reinterpret_cast(args[0])); check_device("Device view", N); static LONG calls; if (first_calls(calls)) @@ -2666,9 +2698,12 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE Translation* translation = nullptr; D3D12_BLEND_DESC blend{}; bool has_blend = false; + D3D12_DEPTH_STENCIL_DESC depth_stencil{}; + bool has_depth_stencil = false; + DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; if (render_mode()) { char why[256] = ""; - translation = stream_translation(*desc, blend, has_blend); + translation = stream_translation(*desc, blend, has_blend, depth_stencil, has_depth_stencil, dsv_format); if (!translation) real_pipeline = build_stream_pipeline(desc, why, sizeof(why)); static LONG built; if (!translation && first_calls(built, 24)) @@ -2676,7 +2711,9 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE } *out = wrap(real_pipeline, pipeline_kind); note_pipeline(static_cast(*out), 86, nullptr, desc->pPipelineStateSubobjectStream, desc->SizeInBytes < 0x2000 ? desc->SizeInBytes : 0x2000, - translation, translation && has_blend ? &blend : nullptr); + translation, translation && has_blend ? &blend : nullptr, + translation && has_depth_stencil ? &depth_stencil : nullptr, + translation ? dsv_format : DXGI_FORMAT_UNKNOWN); return S_OK; } diff --git a/tests/startup_stream_depth.cpp b/tests/startup_stream_depth.cpp new file mode 100644 index 000000000..0eb2af231 --- /dev/null +++ b/tests/startup_stream_depth.cpp @@ -0,0 +1,298 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "startup_stream_setup.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { + +struct alignas(8) StageSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_SHADER_BYTECODE shader; +}; +struct alignas(8) RootSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + ID3D12RootSignature* signature; +}; +struct alignas(8) DepthStencilSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_DEPTH_STENCIL_DESC desc; +}; +static_assert(sizeof(DepthStencilSubobject) == 56); + +struct alignas(8) DepthStencil1Subobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_DEPTH_STENCIL_DESC desc; + BOOL depth_bounds_test; +}; +static_assert(sizeof(DepthStencil1Subobject) == 64); + +struct alignas(8) DsvFormatSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + DXGI_FORMAT format; +}; +static_assert(sizeof(DsvFormatSubobject) == 8); + +struct DepthStream { + StageSubobject ps; + RootSubobject root; + StageSubobject vs; + DepthStencilSubobject ds; + DsvFormatSubobject dsv_format; +}; + +struct DepthStream1 { + StageSubobject ps; + RootSubobject root; + StageSubobject vs; + DepthStencil1Subobject ds1; + DsvFormatSubobject dsv_format; +}; + +using Word = std::uint64_t; +template Word ptr_arg(T* p) { return reinterpret_cast(p); } + +bool read_bytes(const char* path, std::vector& out) +{ + std::ifstream file(path, std::ios::binary); + out.assign(std::istreambuf_iterator(file), {}); + return !out.empty(); +} + +int pick_adapter(bool hardware, ComPtr& adapter) +{ + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; + if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; + ComPtr factory6; + if (FAILED(factory.As(&factory6))) return 77; + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 4; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 4; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + return 0; + } + } +} + +void* create_stream_pso(void* device, ID3D12RootSignature* root, const std::vector& vs, + const std::vector& ps, const D3D12_DEPTH_STENCIL_DESC& ds, bool use_ds1) +{ + using CreateStream = HRESULT (WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + auto create = reinterpret_cast((*static_cast(device))[86]); + void* pso = nullptr; + if (use_ds1) { + DepthStream1 stream{ + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}, + {static_cast(21), ds, FALSE}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT_D32_FLOAT}, + }; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + if (FAILED(create(device, &desc, __uuidof(ID3D12PipelineState), &pso))) return nullptr; + } else { + DepthStream stream{ + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, ds}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT_D32_FLOAT}, + }; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + if (FAILED(create(device, &desc, __uuidof(ID3D12PipelineState), &pso))) return nullptr; + } + return pso; +} + +int clear_depth_desktop(ID3D12Device* desktop, ID3D12Resource* depth_tex) +{ + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + ComPtr heap; + if (FAILED(desktop->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))) return 40; + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + const D3D12_CPU_DESCRIPTOR_HANDLE handle = heap->GetCPUDescriptorHandleForHeapStart(); + desktop->CreateDepthStencilView(depth_tex, &dsv_desc, handle); + + D3D12_COMMAND_QUEUE_DESC qd{}; + ComPtr queue; + ComPtr alloc; + ComPtr list; + ComPtr fence; + if (FAILED(desktop->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue))) || + FAILED(desktop->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc))) || + FAILED(desktop->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), nullptr, IID_PPV_ARGS(&list))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return 41; + + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {depth_tex, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE}; + list->ResourceBarrier(1, &b); + list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + list->ResourceBarrier(1, &b); + if (FAILED(list->Close())) return 42; + + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1))) return 43; + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!ev) return 44; + const bool ok = SUCCEEDED(fence->SetEventOnCompletion(1, ev)) && WaitForSingleObject(ev, 10000) == WAIT_OBJECT_0; + CloseHandle(ev); + return ok ? 0 : 45; +} + +int execute_guest_list(void* queue, void* list, void* fence, UINT64 fence_value) +{ + if (FAILED(static_cast(invoke(list, 10)))) return 50; + void* lists[] = {list}; + invoke(queue, 11, 1, ptr_arg(lists)); + if (FAILED(static_cast(invoke(queue, 15, ptr_arg(fence), fence_value)))) return 51; + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!ev) return 52; + const bool ok = SUCCEEDED(static_cast(invoke(fence, 10, fence_value, reinterpret_cast(ev)))) && + WaitForSingleObject(ev, 10000) == WAIT_OBJECT_0; + CloseHandle(ev); + return ok ? 0 : 53; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 7 && argc != 10) return 2; + std::vector vs_front, vs_back, ps_green, ps_red; + if (!read_bytes(argv[1], vs_front) || !read_bytes(argv[2], vs_back) || + !read_bytes(argv[3], ps_green) || !read_bytes(argv[4], ps_red)) return 3; + const bool hardware = std::strcmp(argv[6], "hardware") == 0; + + ComPtr adapter; + if (const int rc = pick_adapter(hardware, adapter)) return rc; + + std::array parameters{}; + void* guest = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &guest))) return 5; + + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + ComPtr blob; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr))) return 6; + std::ofstream(argv[5], std::ios::binary).write(static_cast(blob->GetBufferPointer()), blob->GetBufferSize()); + ID3D12RootSignature* root = nullptr; + if (FAILED(static_cast(invoke(guest, 16, 0, ptr_arg(blob->GetBufferPointer()), blob->GetBufferSize(), + ptr_arg(&__uuidof(ID3D12RootSignature)), ptr_arg(&root))))) return 7; + + D3D12_DEPTH_STENCIL_DESC ds_less{}; + ds_less.DepthEnable = TRUE; + ds_less.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + ds_less.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + + D3D12_DEPTH_STENCIL_DESC ds_disabled{}; + ds_disabled.DepthEnable = FALSE; + ds_disabled.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + ds_disabled.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + + void* pso_front_less = create_stream_pso(guest, root, vs_front, ps_green, ds_less, false); + void* pso_back_less = create_stream_pso(guest, root, vs_back, ps_red, ds_less, false); + void* pso_front_off = create_stream_pso(guest, root, vs_front, ps_green, ds_disabled, false); + void* pso_back_off = create_stream_pso(guest, root, vs_back, ps_red, ds_disabled, false); + void* pso_front_ds1 = create_stream_pso(guest, root, vs_front, ps_green, ds_less, true); + if (!pso_front_less || !pso_back_less || !pso_front_off || !pso_back_off || !pso_front_ds1) return 9; + if (argc == 7) return 0; + + ComPtr desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; + + constexpr UINT width = 8, height = 4; + StreamTarget state{}; + state.count = 1; + state.attachments[0].row_bytes = width * 4; + + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const float clear_color[] = {0.0f, 0.0f, 1.0f, 1.0f}; + const D3D12_RESOURCE_DESC rtv_tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE rtv_clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.0f, 0.0f, 1.0f, 1.0f}}; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rtv_tex_desc, + D3D12_RESOURCE_STATE_COMMON, &rtv_clear, IID_PPV_ARGS(&state.attachments[0].texture)))) return 21; + + ComPtr depth_tex; + const D3D12_RESOURCE_DESC dsv_tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + DXGI_FORMAT_D32_FLOAT, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + D3D12_CLEAR_VALUE dsv_clear{}; + dsv_clear.Format = DXGI_FORMAT_D32_FLOAT; + dsv_clear.DepthStencil = {1.0f, 0}; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &dsv_tex_desc, + D3D12_RESOURCE_STATE_COMMON, &dsv_clear, IID_PPV_ARGS(&depth_tex)))) return 21; + + const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; Word backing, bytes; } + rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}, + dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}, 0, 0}; + void* dsv_heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr_arg(&rtv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&state.rtv_heap)))) || + FAILED(static_cast(invoke(guest, 14, ptr_arg(&dsv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&dsv_heap))))) return 22; + + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(invoke(state.rtv_heap, 9))}; + const D3D12_CPU_DESCRIPTOR_HANDLE dsv{static_cast(invoke(dsv_heap, 9))}; + const D3D12_RENDER_TARGET_VIEW_DESC rtv_view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_view{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + invoke(guest, 20, ptr_arg(state.attachments[0].texture.Get()), ptr_arg(&rtv_view), rtv.ptr); + invoke(guest, 21, ptr_arg(depth_tex.Get()), ptr_arg(&dsv_view), dsv.ptr); + + D3D12_COMMAND_QUEUE_DESC qd{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(guest, 8, ptr_arg(&qd), ptr_arg(&__uuidof(ID3D12CommandQueue)), ptr_arg(&state.queue)))) || + FAILED(static_cast(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, ptr_arg(&__uuidof(ID3D12CommandAllocator)), ptr_arg(&state.allocator)))) || + FAILED(static_cast(invoke(guest, 73, ptr_arg(list_desc), ptr_arg(state.allocator), 0, ptr_arg(&__uuidof(ID3D12GraphicsCommandList)), ptr_arg(&state.list)))) || + FAILED(static_cast(invoke(guest, 36, 0, 0, ptr_arg(&__uuidof(ID3D12Fence)), ptr_arg(&state.fence))))) return 23; + + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT rect{0, 0, 4, static_cast(height)}; + + auto run_case = [&](UINT64 fence_val, const char* out_path, bool depth_only, void* first_pso, void* second_pso) -> int { + if (const int rc = clear_depth_desktop(desktop.Get(), depth_tex.Get())) return rc; + if (FAILED(static_cast(invoke(state.allocator, 8)))) return 24; + if (FAILED(static_cast(invoke(state.list, 139, ptr_arg(state.allocator))))) return 25; + invoke(state.list, 52, rtv.ptr, ptr_arg(clear_color)); + invoke(state.list, 21, 1, ptr_arg(&viewport)); + invoke(state.list, 22, 1, ptr_arg(&rect)); + invoke(state.list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + if (depth_only) { + invoke(state.list, 50, 0, 0, FALSE, ptr_arg(&dsv)); + } else { + invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, ptr_arg(&dsv)); + } + invoke(state.list, 25, ptr_arg(first_pso)); + invoke(state.list, 12, 3, 1); + if (depth_only) { + invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, ptr_arg(&dsv)); + } + invoke(state.list, 25, ptr_arg(second_pso)); + invoke(state.list, 12, 3, 1); + if (const int rc = execute_guest_list(state.queue, state.list, state.fence, fence_val)) return rc; + return read_stream_target(desktop.Get(), state, out_path); + }; + + if (const int rc = run_case(1, argv[7], false, pso_front_less, pso_back_less)) return rc; + if (const int rc = run_case(2, argv[8], false, pso_front_off, pso_back_off)) return rc; + if (const int rc = run_case(3, argv[9], true, pso_front_ds1, pso_back_less)) return rc; + return 0; +} diff --git a/tests/startup_stream_depth_check.py b/tests/startup_stream_depth_check.py new file mode 100644 index 000000000..e2a079b10 --- /dev/null +++ b/tests/startup_stream_depth_check.py @@ -0,0 +1,72 @@ +"""Check DSV binding (slot 50), view_slot<21, 2>, and stream DEPTH_STENCIL/DEPTH_STENCIL_FORMAT.""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_stream_check import container, gfx2hlsl +from startup_stream_draw_check import pixel, vop1, vop2 + + +def vertex(z_bits): + words = [vop2(0x1a, 1, 129, 0), vop2(0x1b, 1, 130, 1), vop2(0x1b, 2, 130, 0)] + for v in (1, 2): + words.extend([vop1(6, v, 256 + v), vop2(8, v, 244, v), vop2(3, v, 243, v)]) + words.extend([vop1(1, 3, 255), z_bits, vop1(1, 4, 242), 0xf80008cf, 0x04030201, 0xbf810000]) + return container(1, words) + + +def check(directory, consumer, backend): + cache = directory / "cache" + cache.mkdir() + vs_front, vs_back, ps_green, ps_red, root = ( + directory / name for name in ("vs_front", "vs_back", "ps_green", "ps_red", "root") + ) + out_pos, out_neg, out_depthonly = ( + directory / name for name in ("pixels_pos", "pixels_neg", "pixels_depthonly") + ) + vs_front.write_bytes(vertex(0x3e800000)) # z = 0.25f + vs_back.write_bytes(vertex(0x3f400000)) # z = 0.75f + ps_green.write_bytes(pixel(True)) + ps_red.write_bytes(pixel(False)) + + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_D3D12_DEBUG="1", X2W_SHADER_CACHE=str(cache)) + base_args = [consumer, str(vs_front), str(vs_back), str(ps_green), str(ps_red), str(root), backend] + req = subprocess.run(base_args, env=env, capture_output=True, text=True) + if backend == "hardware" and req.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + if req.returncode: + raise RuntimeError(f"request run failed on {backend}: {req.returncode}\n{req.stderr}") + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) + + run = subprocess.run(base_args + [str(out_pos), str(out_neg), str(out_depthonly)], + env=env, capture_output=True, text=True) + print(run.stdout, end="") + for line in run.stderr.splitlines(): + if "debug layer:" in line or "x2w-d3d12-debug " in line: + print(line) + if run.returncode or "-> drawn;" not in run.stderr: + raise RuntimeError(f"depth draw failed on {backend}: {run.returncode}\n{run.stderr}") + assert not re.search(r"x2w-d3d12-debug.*sev=[012]\b", run.stderr), run.stderr + + green = bytes((0, 255, 0, 255)) + red = bytes((255, 0, 0, 255)) + clear = bytes((0, 0, 255, 255)) + expected_pos = (green * 4 + clear * 4) * 4 + expected_neg = (red * 4 + clear * 4) * 4 + expected_depthonly = clear * 32 + + assert out_pos.read_bytes() == expected_pos, f"pos: {out_pos.read_bytes().hex()}" + assert out_neg.read_bytes() == expected_neg, f"neg: {out_neg.read_bytes().hex()}" + assert out_depthonly.read_bytes() == expected_depthonly, f"depthonly: {out_depthonly.read_bytes().hex()}" + print(f"{backend}: depth LESS occluded far red (green), DepthEnable=FALSE overwrote (red), count=0 depth-only occluded far red (clear)") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) From 8f9faa9201eb090d51753c2239a3cea3faae9689 Mon Sep 17 00:00:00 2001 From: Maxim Trusov <146969829+Maxim-Root@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:22:43 +0300 Subject: [PATCH 025/775] shader: accept binary16 and binary64 v_cmpx forms as pixel_aot region openers The v_cmpx region opener (#932, #1335, #1411) accepted the VOPC e32 compares on binary32 and integers and v_cmpx_class_f32. Accept the remaining VOPC v_cmpx forms: all 16 predicates on binary16 and on binary64, v_cmpx_class_f16 and v_cmpx_class_f64 (34 forms; every VOPC v_cmpx form of gfx1013 is now counted). Each lowers exactly like the e32 v_cmp of the same kind through one shared helper: f16_comparison/f16_class (moved out of the v_cmp_f16 and v_cmp_class_f16 branches) and f64_comparison (moved out of the v_cmp_*_f64 branch). The binary64 forms keep the declared binary64 denormal entry state. e64, SDWA, SGPR VSRC1 and source modifiers stay refused. Draws on WARP and hardware: four binary16 predicate groups on pairs whose high halves give a different binary32 relation, a binary16 class group, and five binary64 groups on every cmp_f64 word row, each with wrong references that must mismatch. The LLVM 15 round trip covers the ten programs, and form_coverage_check counts 95 v_cmpx forms. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 4 +- tests/form_coverage_check.py | 15 ++- tests/pixel_aot_check.py | 242 +++++++++++++++++++++++++++++++++-- tools/pixel_aot.py | 159 ++++++++++++++--------- 4 files changed, 333 insertions(+), 87 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 0173d695e..9573dd930 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -708,9 +708,9 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^pixel_aot_exec_regions_(warp|hardware)$' -V ``` -The same region can also open with `s_mov_b64 s[a:b], exec` immediately followed by a VOPC `_e32` `v_cmpx` on binary32 or 16-, 32- or 64-bit integer operands (issue #932): all 16 binary32 predicates, the 8 signed and 8 unsigned integer predicates at 32 and 64 bits and the 6 signed and 6 unsigned ones at 16 bits (gfx10 has no 16-bit `f` or `t`), and `v_cmpx_class_f32`, 61 forms. `v_cmpx_class_f32` tests the class of the raw binary32 encoding of src0 against the class mask in VSRC1, as the e32 `v_cmp_class_f32` does. A 16-bit comparison reads the low 16 bits of each operand, and a 64-bit one takes the VGPR-pair, SGPR-pair and inline-constant sources of the 64-bit `v_cmp` with a VGPR pair as VSRC1. The [AMD RDNA 2 ISA guide](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) (§6.2.2, §12.9) defines `v_cmpx` as writing its comparison to EXEC, and a thread writes only while its EXEC bit is set. From the known entry mask the translator therefore takes the new mask as the entry mask intersected with the comparison, the same lane condition as `v_cmp` plus `s_and_saveexec_b64`. That intersection rule comes from the ISA text and from LLVM's gfx10.3 rewrite of `v_cmp` plus `s_and_saveexec` into this pattern; no gfx1013 hardware run checks it. The save must hold the entry mask (not a whole-quad mask), must directly precede the `v_cmpx` and must not overlap a pending scalar load, and the region closes with `s_mov_b64 exec, s[a:b]` or `s_or_b64 exec, exec, s[a:b]` on the saved pair; the optional `s_cbranch_execz` must sit right after the `v_cmpx` and target that restore. `v_cmpx` writes neither VCC nor SCC, so both keep their tracked values through the region; `s_mov_b64` leaves SCC, while `s_or_b64` writes it from the restored mask, which is untracked, so an SCC reader after the `s_or_b64` close rejects. The region body follows the rules above. `_e64`, SDWA, binary16 and binary64 forms (including their class tests), a VSRC1 that is not a VGPR (a VGPR pair at 64 bits), source modifiers, chained or nested `v_cmpx`, wave32 saves and kill shapes all reject; the else transition follows the rules above. +The same region can also open with `s_mov_b64 s[a:b], exec` immediately followed by a VOPC `_e32` `v_cmpx` on binary16, binary32, binary64 or 16-, 32- or 64-bit integer operands (issue #932): all 16 predicates at each of binary16, binary32 and binary64, the 8 signed and 8 unsigned integer predicates at 32 and 64 bits and the 6 signed and 6 unsigned ones at 16 bits (gfx10 has no 16-bit `f` or `t`), and the three class tests `v_cmpx_class_f16`, `v_cmpx_class_f32` and `v_cmpx_class_f64`, 95 forms: every VOPC `v_cmpx` form of gfx1013. `v_cmpx_class_f32` tests the class of the raw binary32 encoding of src0 against the class mask in VSRC1, as the e32 `v_cmp_class_f32` does. The binary16 forms and `v_cmpx_class_f16` share the lowering of the e32 `v_cmp_f16` and `v_cmp_class_f16`: they read the low 16 bits of each source (a literal must fit in 16 bits), treat a NaN in either one as unordered, and take the class mask from the VGPR in VSRC1. The binary64 forms and `v_cmpx_class_f64` share the lowering of the e32 `v_cmp_*_f64` and `v_cmp_class_f64` (one helper, `f64_comparison`, serves both): they compare the raw words with the `cmp_f64` helpers and no HLSL double, take a VGPR pair as VSRC1 (a VGPR class mask for the class test) and, like `v_cmp_*_f64`, need the declared binary64 denormal entry state. A 16-bit comparison reads the low 16 bits of each operand, and a 64-bit one takes the VGPR-pair, SGPR-pair and inline-constant sources of the 64-bit `v_cmp` with a VGPR pair as VSRC1. The [AMD RDNA 2 ISA guide](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) (§6.2.2, §12.9) defines `v_cmpx` as writing its comparison to EXEC, and a thread writes only while its EXEC bit is set. From the known entry mask the translator therefore takes the new mask as the entry mask intersected with the comparison, the same lane condition as `v_cmp` plus `s_and_saveexec_b64`. That intersection rule comes from the ISA text and from LLVM's gfx10.3 rewrite of `v_cmp` plus `s_and_saveexec` into this pattern; no gfx1013 hardware run checks it. The save must hold the entry mask (not a whole-quad mask), must directly precede the `v_cmpx` and must not overlap a pending scalar load, and the region closes with `s_mov_b64 exec, s[a:b]` or `s_or_b64 exec, exec, s[a:b]` on the saved pair; the optional `s_cbranch_execz` must sit right after the `v_cmpx` and target that restore. `v_cmpx` writes neither VCC nor SCC, so both keep their tracked values through the region; `s_mov_b64` leaves SCC, while `s_or_b64` writes it from the restored mask, which is untracked, so an SCC reader after the `s_or_b64` close rejects. The region body follows the rules above. `_e64`, SDWA, a VSRC1 that is not a VGPR (a VGPR pair at 64 bits), source modifiers, chained or nested `v_cmpx`, wave32 saves and kill shapes all reject; the else transition follows the rules above. -The fixtures draw the ramp region with the `s_mov_b64` restore, the `s_or_b64` restore and the skip on mixed (0.5), full (10) and empty (-1) masks, and each must match all 64 pixels; a reversed predicate and a mask-free copy of the body must mismatch on the mixed mask. A second program sets VCC and SCC before the region and reads both after the `s_mov_b64` close; references that take VCC from the `v_cmpx` comparison or invert SCC must mismatch. Twelve programs of four regions each draw every accepted predicate against the truth tables of the existing `v_cmp` draws (less, equal, greater and, for binary32, unordered inputs), alternating the two restores; the signed shader against the unsigned truth table must mismatch. The 16-bit operand pairs have high halves that disagree with their low halves, so a signed 16-bit reference read as unsigned or over all 32 bits must mismatch. Four more programs run each 64-bit predicate over the operand shapes and word patterns of the 64-bit `v_cmp` draws against the same reference, and the signed shader against the unsigned reference must mismatch. Two more programs open the ramp region with `v_cmpx_class_f32_e32` on the +normal class of `s44 - sample.x`, which holds exactly where `s44 > sample.x`. Through both restores, they must match the same masked pixels on the mixed, full and empty masks. The -normal mask (the reversed region) and a mask-free body must mismatch. A fourth program opens four uniform class regions on the inputs of the `v_cmp_class_f32` draw: +inf against its own bit, a quiet NaN against both NaN bits, -0 against the +0 bit and a positive denormal against its bit. A wrong result in any channel must mismatch. Every fixture is also assembled and disassembled with LLVM 15 for gfx1013 and must lower identically. The translation controls cover the rejections listed above, wrong skip targets, an overwritten save pair and unsupported body instructions. +The fixtures draw the ramp region with the `s_mov_b64` restore, the `s_or_b64` restore and the skip on mixed (0.5), full (10) and empty (-1) masks, and each must match all 64 pixels; a reversed predicate and a mask-free copy of the body must mismatch on the mixed mask. A second program sets VCC and SCC before the region and reads both after the `s_mov_b64` close; references that take VCC from the `v_cmpx` comparison or invert SCC must mismatch. Sixteen programs of four regions each draw every accepted predicate against the truth tables of the existing `v_cmp` draws (less, equal, greater and, for binary16 and binary32, unordered inputs), alternating the two restores; the signed shader against the unsigned truth table must mismatch. The 16-bit operand pairs have high halves that disagree with their low halves, so a signed 16-bit reference read as unsigned or over all 32 bits must mismatch. The binary16 operand pairs cover less, equal, -0 against +0, greater, denormals, infinities and a NaN on either side, with high halves chosen so that a binary32 read of the whole word gives another relation; references taken from that binary32 relation or with less and greater swapped must mismatch wherever the truth row changes. Four more programs run each 64-bit predicate over the operand shapes and word patterns of the 64-bit `v_cmp` draws against the same reference, and the signed shader against the unsigned reference must mismatch. Two more programs open the ramp region with `v_cmpx_class_f32_e32` on the +normal class of `s44 - sample.x`, which holds exactly where `s44 > sample.x`. Through both restores, they must match the same masked pixels on the mixed, full and empty masks. The -normal mask (the reversed region) and a mask-free body must mismatch. A fourth program opens four uniform class regions on the inputs of the `v_cmp_class_f32` draw: +inf against its own bit, a quiet NaN against both NaN bits, -0 against the +0 bit and a positive denormal against its bit. A wrong result in any channel must mismatch. A fifth program runs the same four regions as `v_cmpx_class_f16` on binary16 +inf, a quiet NaN, -0 and a positive denormal in the low halves, whose high halves give a binary32 class outside each mask; a wrong result in any channel and the binary32 class of the whole words must mismatch. Five more programs run every binary64 predicate and the binary64 class test as openers, with the operand shapes and class masks of the e32 `v_cmp_*_f64` draw, on all of its word rows against the same reference; those rows separate the integer order of the words, unequal signed zeros, flushed denormals and a NaN test on the high word only. Swapped operands on -1.0 against -2.0 and flipped class channels must mismatch. Every fixture is also assembled and disassembled with LLVM 15 for gfx1013 and must lower identically. The translation controls cover the rejections listed above, wrong skip targets, an overwritten save pair and unsupported body instructions. ```powershell cmake --build --preset dev --target offscreen_check diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 7c8e349e1..1f5a2ba06 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -404,17 +404,18 @@ def check_shader_records(): # Each name is counted once as VOPC and once as VOP3; the five sets must not share a name. assert len(compare_forms) == 2 * (len(narrow_int) + len(int64) + len(f16_compares) + len(f32_compares) + len(f64_compares)), len(compare_forms) - # VOPC e32 regions support binary32 and integer predicates and the binary32 class test, but not binary16, - # binary64 or their class tests. - compare_neighbours = {"v_cmpx_lt_f16", "v_cmpx_lt_f64", "v_cmpx_class_f16", "v_cmpx_class_f64"} - # v_cmpx regions (issue #932): every binary32 and integer predicate and v_cmpx_class_f32 count in VOPC (e32) only. - cmpx_forms = ({("VOPC", f"v_cmpx_{op}_f32") for op in pixel.PREDICATES} + # VOPC e32 regions support every binary16, binary32, binary64 and integer predicate and the binary16, binary32 and + # binary64 class tests, so no VOPC v_cmpx form is left as a neighbour; the e64 spellings stay uncovered (below). + compare_neighbours = set() + # v_cmpx regions (issue #932): every binary16, binary32, binary64 and integer predicate and the three class tests + # count in VOPC (e32) only. + cmpx_forms = ({("VOPC", f"v_cmpx_{op}_{kind}") for op in pixel.PREDICATES for kind in ("f16", "f32", "f64")} | {("VOPC", f"v_cmpx_{op}_{kind}") for op in pixel.INT_PREDICATES for kind in ("i32", "u32", "i64", "u64")} | {("VOPC", f"v_cmpx_{op}_{kind}") for op in ("eq", "ne", "lt", "le", "gt", "ge") for kind in ("i16", "u16")} - | {("VOPC", "v_cmpx_class_f32")}) - assert len(cmpx_forms) == 61, len(cmpx_forms) + | {("VOPC", f"v_cmpx_class_{kind}") for kind in ("f16", "f32", "f64")}) + assert len(cmpx_forms) == 95, len(cmpx_forms) for name in ("gfx1013.tsv", "rdna2.tsv"): reference = fc.load_reference(name) assert compare_forms | {("VOPC", n) for n in compare_neighbours} <= reference, name diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 2403950e2..8b5a27f85 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -764,9 +764,10 @@ def cmpx_predicate_group(kind, first): """Four v_cmpx regions, one per predicate, each setting one channel to 1.0 where `s44 v18` holds. Mirrors predicate_group and int_predicate_group: v18 copies s45 and v19 copies s47 (1.0). The regions - alternate the s_mov_b64 and s_or_b64 restores, so both closes are drawn for every kind. + alternate the s_mov_b64 and s_or_b64 restores, so both closes are drawn for every kind. The integer and + binary16 kinds copy s45 with v_mov_b32, so the high half of the word reaches the comparison unchanged. """ - predicates = PREDICATES if kind == "f32" else INT_PREDICATES + predicates = PREDICATES if kind in ("f32", "f16") else INT_PREDICATES copy = (["v_sub_f32_e64 v18, s45, 0", "v_sub_f32_e64 v19, s47, 0"] if kind == "f32" else ["v_mov_b32_e32 v18, s45", "v_mov_b32_e32 v19, s47"]) body = copy + [f"v_mov_b32_e32 v{12 + channel}, 0" for channel in range(4)] @@ -776,9 +777,11 @@ def cmpx_predicate_group(kind, first): return with_constants(body) -# The 16-bit kinds have no f/t forms: groups starting at lt and le draw lt, eq, le, gt, ne and ge. +# The 16-bit integer kinds have no f/t forms: groups starting at lt and le draw lt, eq, le, gt, ne and ge. +# binary16 has all 16 predicates, as binary32. CMPX_PREDICATE_GROUPS = tuple((kind, first) for kind, firsts in (("f32", (0, 4, 8, 12)), ("i32", (0, 4)), - ("u32", (0, 4)), ("i16", (1, 3)), ("u16", (1, 3))) + ("u32", (0, 4)), ("i16", (1, 3)), ("u16", (1, 3)), + ("f16", (0, 4, 8, 12))) for first in firsts) # Pairs (s44, s45) for the 16-bit kinds: the high halves differ, so only the low 16 bits may decide. CMPX_INT16_PAIRS = ((0x12348000, 0xabcd0000), (0xffff1234, 0x00001234), (0x00000001, 0xffff0000), @@ -822,16 +825,69 @@ def cmpx_class_region(restore=CMPX_MOV_RESTORE, classes=CMPX_CLASS_POSITIVE_NORM CMPX_CLASS_MASKS = (0x200, 3, 0x40, 0x80) -def cmpx_class_group(masks=CMPX_CLASS_MASKS): - """Four v_cmpx_class_f32 regions, each setting one channel to 1.0 when s44+channel is in its class mask.""" +def cmpx_class_group(masks=CMPX_CLASS_MASKS, kind="f32"): + """Four v_cmpx_class regions, each setting one channel to 1.0 when s44+channel is in its class mask.""" body = ["v_mov_b32_e32 v19, 1.0"] + [f"v_mov_b32_e32 v{12 + channel}, 0" for channel in range(4)] for channel, classes in enumerate(masks): body += [f"v_mov_b32_e32 v18, {classes if classes <= 64 else hex(classes)}", CMPX_SAVE, - f"v_cmpx_class_f32_e32 s{44 + channel}, v18", f"v_mov_b32_e32 v{12 + channel}, v19", + f"v_cmpx_class_{kind}_e32 s{44 + channel}, v18", f"v_mov_b32_e32 v{12 + channel}, v19", CMPX_MOV_RESTORE if channel % 2 == 0 else CMPX_OR_RESTORE] return with_constants(body) +def half_bits_value(bits): + """The binary16 value of the low 16 bits of a word.""" + return struct.unpack("= sign + if magnitude > inf: + return 0x2 if value & quiet else 0x1 + if magnitude == inf: + return 0x4 if negative else 0x200 + if magnitude >= normal: + return 0x8 if negative else 0x100 + if magnitude: + return 0x10 if negative else 0x80 + return 0x20 if negative else 0x40 + + +def cmpx_float_relation(left, right): + """0, 1, 2 or 3 for less, equal, greater or unordered: the bit of the predicate index that holds.""" + if math.isnan(left) or math.isnan(right): + return 3 + return 0 if left < right else (1 if left == right else 2) + + +# binary16 (s44, s45) words for the v_cmpx__f16 groups, one per relation shape: less, equal, signed zero, greater, +# denormals, infinities and a NaN on either side (a signaling one on the right). The high halves are chosen so a +# binary32 read of the whole word gives a different relation; check_cmpx_controls asserts both claims. +CMPX_F16_PAIRS = (("lt", 0x4000bc00, 0xc0003c00), ("eq", 0x12343c00, 0xabcd3c00), + ("signed-zero", 0x00008000, 0x7fc00000), ("gt", 0xbf804000, 0x3f80c000), + ("denormal", 0x3f800001, 0x00000002), ("inf", 0x0000fc00, 0x00007c00), + ("left-nan", 0x3f807e00, 0x3f803c00), ("right-nan", 0x40003c00, 0x3f807c01)) + + +def cmpx_f16_relation(left, right, *, whole_word=False): + """The relation of the low halves as binary16, or with whole_word=True of the full words as binary32.""" + if whole_word: + return cmpx_float_relation(*struct.unpack("<2f", struct.pack("<2I", left, right))) + return cmpx_float_relation(half_bits_value(left), half_bits_value(right)) + + +# v_cmpx_class_f16 regions on the CMPX_CLASS_MASKS properties in binary16: +inf against its own bit, a quiet NaN +# against both NaN bits, -0 against the +0 bit and a positive denormal against its bit. Each high half makes the +# binary32 class of the whole word differ (+normal, +normal, +normal, -denormal), so a 32-bit read gives 0 in every +# channel. +CMPX_CLASS_F16_BITS = (0x12347c00, 0x3f807e00, 0x40008000, 0x80000001) + + def cmpx_observables(): """VCC and SCC written before a v_cmpx region keep their values after the s_mov_b64 restore. @@ -925,6 +981,32 @@ def check_cmpx_draw(directory, compiler, renderer, backend): case.write_bytes(class_constants + struct.pack("<4f", *class_expected) * 64) cases.append((case, "pass")) run_pixel_batch(renderer, backend, shader, cases) + # The same class regions as v_cmpx_class_f16 on the low halves of CMPX_CLASS_F16_BITS. Wrong references: each + # channel flipped, and the binary32 class of the whole words (0 in every channel). + source.write_text(translate(cmpx_class_group(kind="f16")), encoding="ascii") + compile_shader(compiler, source, shader) + class_constants = bytearray(256) + struct.pack_into("<4I", class_constants, 12, *CMPX_CLASS_F16_BITS) + class_expected = [float(class_bit(bits, half=True) & classes != 0) + for bits, classes in zip(CMPX_CLASS_F16_BITS, CMPX_CLASS_MASKS)] + assert class_expected == [1.0, 1.0, 0.0, 1.0], class_expected + whole_word = [float(class_bit(bits, half=False) & classes != 0) + for bits, classes in zip(CMPX_CLASS_F16_BITS, CMPX_CLASS_MASKS)] + assert whole_word == [0.0] * 4, whole_word + cases = [] + for k in range(4): + wrong = list(class_expected) + wrong[k] = 1.0 - wrong[k] + case = directory / f"cmpx-class-f16-group-wrong-{k}.case" + case.write_bytes(class_constants + struct.pack("<4f", *wrong) * 64) + cases.append((case, "mismatch")) + case = directory / "cmpx-class-f16-group-as-32-bit.case" + case.write_bytes(class_constants + struct.pack("<4f", *whole_word) * 64) + cases.append((case, "mismatch")) + case = directory / "cmpx-class-f16-group.case" + case.write_bytes(class_constants + struct.pack("<4f", *class_expected) * 64) + cases.append((case, "pass")) + run_pixel_batch(renderer, backend, shader, cases) # VCC and SCC from before the region, on mixed, full and empty masks; SCC is 1 only for 0.5. source.write_text(translate(cmpx_observables()), encoding="ascii") compile_shader(compiler, source, shader) @@ -958,6 +1040,29 @@ def check_cmpx_draw(directory, compiler, renderer, backend): case = directory / f"cmpx-{kind}-{first}-{label}.case" write_case(case, constants, tuple((op >> relation) & 1 for op in range(first, first + 4))) cases.append((case, "pass")) + elif kind == "f16": + # binary16 on the low halves. Wrong references: the binary32 relation of the whole words, and the + # less and greater rows swapped (a reversed predicate), wherever this group's truth row differs. + wrong_rows = 0 + for label, left, right in CMPX_F16_PAIRS: + relation = cmpx_f16_relation(left, right) + whole = cmpx_f16_relation(left, right, whole_word=True) + assert whole != relation, (label, relation, whole) + constants = bytearray(256) + struct.pack_into("> relation) & 1 for op in range(first, first + 4)) + case = directory / f"cmpx-f16-{first}-{label}.case" + case.write_bytes(constants + struct.pack("<4f", *row) * 64) + cases.append((case, "pass")) + swapped = {0: 2, 2: 0}.get(relation, relation) + for wrong_label, wrong_relation in (("as-32-bit", whole), ("reversed", swapped)): + wrong = tuple((op >> wrong_relation) & 1 for op in range(first, first + 4)) + if wrong != row: + case = directory / f"cmpx-f16-{first}-{label}-{wrong_label}.case" + case.write_bytes(constants + struct.pack("<4f", *wrong) * 64) + cases.append((case, "mismatch")) + wrong_rows += 1 + assert wrong_rows >= 4, (first, wrong_rows) else: for left, right in (CMPX_INT16_PAIRS if kind in ("i16", "u16") else int_pairs): lv, rv = left, right @@ -1019,6 +1124,43 @@ def check_cmpx_draw(directory, compiler, renderer, backend): except AssertionError as error: error.add_note(f"64-bit v_cmpx draw on {backend}, kind={kind}, group={group}") raise + # binary64 v_cmpx regions against the cmpf64 reference, on every CMPF64_WORDS row: the rows separate the + # unsigned integer order, unequal signed zeros, flushed denormals and a high-word-only NaN test. + for group in CMPXF64_GROUPS: + source.write_text(translate_f64(cmpxf64_group(group)), encoding="ascii") + compile_shader(compiler, source, shader) + cases = [] + for index, words in enumerate(CMPF64_WORDS): + constants = bytearray(256) + struct.pack_into("<4I", constants, 12, *words) + case = directory / f"cmpxf64-{group}-{index}.case" + write_case(case, bytes(constants), cmpf64_expected("e32", group, words), integer_rt=True) + cases.append((case, "pass")) + # Wrong references on one row each: the operands swapped for group 0 on -1.0 against -2.0 (row 3), and + # every class channel flipped on the first row. + wrong_row = 3 if group == 0 else 0 if group == "class" else None + if wrong_row is not None: + words = CMPF64_WORDS[wrong_row] + right = cmpf64_expected("e32", group, words) + if group == 0: + wrong = tuple(as_float(0x3f800000 if cmpf64_truth(CMPF64_PREDICATES[channel], + *reversed([cmpf64_operand(t, words) for t in + cmpf64_sources(CMPF64_SHAPES[channel % 4], + "e32")])) else 0) + for channel in range(4)) + else: + wrong = tuple(as_float(0x3f800000) if value == 0 else as_float(0) for value in right) + assert wrong != right, group + constants = bytearray(256) + struct.pack_into("<4I", constants, 12, *words) + case = directory / f"cmpxf64-{group}-wrong.case" + write_case(case, bytes(constants), wrong, integer_rt=True) + cases.append((case, "mismatch")) + try: + run_pixel_batch(renderer, backend, shader, cases) + except AssertionError as error: + error.add_note(f"binary64 v_cmpx draw on {backend}, group={group}") + raise return 0 @@ -3410,6 +3552,25 @@ def cmpf64_expected(encoding, group, words): CMPF64_GROUPS = tuple((encoding, group) for encoding in ("e32", "e64") for group in (0, 1, 2, 3, "class")) +CMPXF64_GROUPS = (0, 1, 2, 3, "class") + + +def cmpxf64_group(group): + """The e32 cmpf64 group with each comparison opening a v_cmpx region that sets its channel to 1.0 (v22). + + Same predicates, operand shapes and class masks as cmpf64_group("e32", group), so cmpf64_expected("e32", ...) + is the reference. The regions alternate the s_mov_b64 and s_or_b64 restores. + """ + body = [f"v_mov_b32_e32 v{12 + channel}, 0" for channel in range(4)] + for channel in range(4): + if group == "class": + source, classes = CMPF64_CLASS["e32"][channel] + body += [f"v_mov_b32_e32 v23, {classes}", CMPX_SAVE, f"v_cmpx_class_f64_e32 {source}, v23"] + else: + src0, src1 = cmpf64_sources(CMPF64_SHAPES[(channel + group) % 4], "e32") + body += [CMPX_SAVE, f"v_cmpx_{CMPF64_PREDICATES[4 * group + channel]}_f64_e32 {src0}, {src1}"] + body += [f"v_mov_b32_e32 v{12 + channel}, v22", CMPX_MOV_RESTORE if channel % 2 == 0 else CMPX_OR_RESTORE] + return cmp64_program(body) def cmpf64_program(encoding, group): @@ -3424,6 +3585,36 @@ def check_cmpf64_controls(): translate_f64(program) forms.update(line.split()[0] for line in program if line.startswith("v_cmp_")) assert forms == {f"v_cmp_{op}_f64_{enc}" for op in (*CMPF64_PREDICATES, "class") for enc in ("e32", "e64")}, forms + # v_cmpx regions on binary64 (issue #932 follow-up): every predicate and the class test as VOPC e32 openers. + cmpx_forms = set() + for group in CMPXF64_GROUPS: + program = cmpxf64_group(group) + text = translate_f64(program) + assert text[text.index(" main("):].count(" ? ") == 4, group + cmpx_forms.update(line.split()[0] for line in program if line.startswith("v_cmpx_")) + expect_value_error(translate_int, program, "binary64 denormal mode unknown at entry") + assert cmpx_forms == {f"v_cmpx_{op}_f64_e32" for op in (*CMPF64_PREDICATES, "class")}, cmpx_forms + + def opener_lowering(first): + """The binary64 declarations and predicate emitted for `first`, with the cmp numbers dropped.""" + program = cmp64_program(["v_mov_b32_e32 v23, 0x204", *first]) + return [re.sub(r"cmp\d+", "cmp", line.strip()) for line in translate_f64(program).splitlines() + if re.match(r"\s+(uint2?|bool) cmp\d+", line)] + + # Each binary64 opener lowers like the e32 v_cmp of the same predicate on the same sources. + for compare, plain in (("v_cmpx_lt_f64_e32 v[18:19], v[20:21]", "v_cmp_lt_f64_e32 vcc_lo, v[18:19], v[20:21]"), + ("v_cmpx_nge_f64_e32 s[44:45], v[20:21]", "v_cmp_nge_f64_e32 vcc_lo, s[44:45], v[20:21]"), + ("v_cmpx_u_f64_e32 -2.0, v[20:21]", "v_cmp_u_f64_e32 vcc_lo, -2.0, v[20:21]"), + ("v_cmpx_class_f64_e32 v[20:21], v23", "v_cmp_class_f64_e32 vcc_lo, v[20:21], v23")): + opened = opener_lowering([CMPX_SAVE, compare, "v_mov_b32_e32 v12, v22", CMPX_MOV_RESTORE]) + reference = opener_lowering([plain, "v_cndmask_b32_e32 v12, 0, v22, vcc_lo"]) + assert opened and opened == reference, (compare, opened, reference) + # Refused: e64 and SDWA spellings, an SGPR pair or a single VGPR as VSRC1, source modifiers, an SGPR class mask. + for compare in ("v_cmpx_lt_f64_e64 v[18:19], v[20:21]", "v_cmpx_lt_f64_e32 v[18:19], s[46:47]", + "v_cmpx_lt_f64_e32 v[18:19], v20", "v_cmpx_lt_f64_e32 -v[18:19], v[20:21]", + "v_cmpx_lt_f64_e32 |v[18:19]|, v[20:21]", "v_cmpx_class_f64_e32 v[18:19], s46", + "v_cmpx_class_f64_e64 v[18:19], 0x204", "v_cmpx_lt_f64"): + must_reject(translate_f64, cmp64_program([CMPX_SAVE, compare, "v_mov_b32_e32 v12, v22", CMPX_MOV_RESTORE])) # The forms need the declared binary64 denormal state, because MODE[7:6] could flush denormal inputs. for encoding, group in (("e32", 0), ("e64", "class")): expect_value_error(translate_int, cmpf64_program(encoding, group), "binary64 denormal mode unknown at entry") @@ -3470,7 +3661,9 @@ def error(line, message): error("v_cmp_class_f64_e32 vcc_lo, v[18:19], 3", "VOPC e32 src1 must be a VGPR") error("v_cmp_class_f64_e64 s52, v[18:19], 1.0", "Unsupported class mask") error("v_cmp_lt_f64_e64 s52, v[60:61], v[20:21]", "Untracked 64-bit comparison source: v[60:61]") - for line in ("v_cmp_lt_f64 vcc_lo, v[18:19], v[20:21]", "v_cmpx_lt_f64_e32 v[18:19], v[20:21]", + # A binary64 v_cmpx opens a region only directly after the entry-mask save (as the 64-bit integer forms). + error("v_cmpx_lt_f64_e32 v[18:19], v[20:21]", "Unsupported v_cmpx execution mask save") + for line in ("v_cmp_lt_f64 vcc_lo, v[18:19], v[20:21]", "v_cmp_lt_f64_sdwa vcc_lo, v[18:19], v[20:21]", "v_cmp_lt_f64_e64 s52, v[18:19], v[20:21] clamp"): error(line, invalid + "v[20:21] clamp" if line.endswith("clamp") else "Unsupported instruction") # A masked region and a pending scalar load. @@ -10952,7 +11145,17 @@ def selects(program): assert selects(cmpx_class_region(restore)) == 2 assert selects(cmpx_class_group()) == 4 assert translate(cmpx_class_group()).count("(class32(") == 4 - # Each accepted comparison kind lowers like the v_cmp of the same kind. + assert selects(cmpx_class_group(kind="f16")) == 4 + assert [cmpx_f16_relation(left, right) for _, left, right in CMPX_F16_PAIRS] == [0, 1, 1, 2, 0, 0, 3, 3] + assert all(cmpx_f16_relation(left, right, whole_word=True) != cmpx_f16_relation(left, right) + for _, left, right in CMPX_F16_PAIRS) + assert translate(cmpx_class_group(kind="f16")).count("(class16(") == 4 + # Each accepted comparison kind lowers like the v_cmp of the same kind: every binary16 predicate, with a + # register, an inline constant and a 16-bit literal as src0, and the binary16 class test. + f16_pairs = [(f"v_cmpx_{op}_f16_e32 {src0}, v12", f"v_cmp_{op}_f16_e32 vcc_lo, {src0}, v12") + for op in PREDICATES for src0 in ("s44", "v13", "-1.0", "0x7c01")] + f16_pairs += [(f"v_cmpx_class_f16_e32 {src0}, v12", f"v_cmp_class_f16_e32 vcc_lo, {src0}, v12") + for src0 in ("s44", "v13", "0.5", "-4", "0x7c00")] for compare, plain in (("v_cmpx_lt_f32_e32 s44, v12", "v_cmp_lt_f32_e32 vcc_lo, s44, v12"), ("v_cmpx_ge_i32_e32 v13, v12", "v_cmp_ge_i32_e32 vcc_lo, v13, v12"), ("v_cmpx_ne_u32_e32 0x3f000000, v12", "v_cmp_ne_u32_e32 vcc_lo, 0x3f000000, v12"), @@ -10960,7 +11163,8 @@ def selects(program): ("v_cmpx_gt_i16_e32 v13, v12", "v_cmp_gt_i16_e32 vcc_lo, v13, v12"), ("v_cmpx_le_u16_e32 0x8000, v12", "v_cmp_le_u16_e32 vcc_lo, 0x8000, v12"), ("v_cmpx_class_f32_e32 s44, v12", "v_cmp_class_f32_e32 vcc_lo, s44, v12"), - ("v_cmpx_class_f32_e32 0x200, v12", "v_cmp_class_f32_e32 vcc_lo, 0x200, v12")): + ("v_cmpx_class_f32_e32 0x200, v12", "v_cmp_class_f32_e32 vcc_lo, 0x200, v12"), + *f16_pairs): expr = next(line for line in translate(cmpx_region(compare=compare)).splitlines() if "bool cmp" in line) reference = next(line for line in translate(uncompressed_export([plain])).splitlines() if "bool cmp" in line) assert expr.split(" = ", 1)[1] == reference.split(" = ", 1)[1], (compare, expr, reference) @@ -11010,16 +11214,24 @@ def selects(program): expect_value_error(translate, [CMPX_MOV_RESTORE.replace("60:61", "58:59") if line == "s_or_b64 exec, exec, s[60:61]" else line for line in masked_region()], "Unexpected execution mask restore") must_reject(translate, [line for line in region if line != CMPX_MOV_RESTORE]) - # Out of scope for this stage: e64, SDWA, f16/f64 and their class forms, VSRC1 not a VGPR (a pair at 64 bits), - # the 16-bit f/t forms gfx10 lacks, a float token on a 16-bit integer, and source modifiers. + # Out of scope for this stage: e64, SDWA, VSRC1 not a VGPR (a pair at 64 bits; binary64 refusals are in + # check_cmpf64_controls), the 16-bit f/t forms gfx10 lacks, a float token on a 16-bit integer, source + # modifiers and, for binary16, a literal wider than 16 bits. for compare in ("v_cmpx_gt_f32_e64 s44, v12", "v_cmpx_gt_f32_sdwa s44, v12 src0_sel:DWORD src1_sel:DWORD", - "v_cmpx_gt_f16_e32 s44, v12", "v_cmpx_gt_f64_e32 s[44:45], v[12:13]", "v_cmpx_t_i16_e32 s44, v12", "v_cmpx_gt_i16_e32 1.0, v12", "v_cmpx_gt_u64_e32 s[44:45], v12", "v_cmpx_gt_i64_e32 v[12:13], s[44:45]", "v_cmpx_gt_u16_e64 s44, v12", "v_cmpx_class_f32_e64 s44, v12", "v_cmpx_class_f32_e32 v12, s44", "v_cmpx_class_f32_e32 -v13, v12", "v_cmpx_class_f32_e32 |v13|, v12", "v_cmpx_class_f32_sdwa s44, v12 src0_sel:DWORD src1_sel:DWORD", - "v_cmpx_class_f16_e32 s44, v12", "v_cmpx_class_f64_e32 s[44:45], v12", + "v_cmpx_gt_f16_e64 s44, v12", "v_cmpx_gt_f16_sdwa s44, v12 src0_sel:WORD_0 src1_sel:WORD_0", + "v_cmpx_gt_f16_e32 v12, s44", "v_cmpx_gt_f16_e32 -v13, v12", "v_cmpx_gt_f16_e32 -s44, v12", + "v_cmpx_gt_f16_e32 |v13|, v12", "v_cmpx_gt_f16_e32 abs(v13), v12", + "v_cmpx_gt_f16_e32 neg(v13), v12", "v_cmpx_gt_f16_e32 0x10000, v12", "v_cmpx_gt_f16_e32 s44", + "v_cmpx_gt_f16 s44, v12", "v_cmpx_class_f16_e64 s44, v12", + "v_cmpx_class_f16_sdwa s44, v12 src0_sel:WORD_0 src1_sel:DWORD", + "v_cmpx_class_f16_e32 v12, s44", "v_cmpx_class_f16_e32 v12, 0x200", + "v_cmpx_class_f16_e32 -v13, v12", "v_cmpx_class_f16_e32 |v13|, v12", + "v_cmpx_class_f16_e32 0x10000, v12", "v_cmpx_gt_f32_e32 v12, s44", "v_cmpx_gt_f32_e32 -v13, v12", "v_cmpx_gt_f32_e32 |v13|, v12", "v_cmpx_gt_f32 s44, v12", "v_cmpx_gt_f32_e32 s44"): @@ -15578,6 +15790,8 @@ def check_binary(directory, assembler, objcopy, library): fixtures.append((cmpx_skip_asm(), translate, "gfx1013", "", cmpx_skip())) fixtures.extend((program, translate) for program in (cmpx_class_region(), cmpx_class_region(CMPX_OR_RESTORE), cmpx_class_group())) + fixtures.extend((cmpxf64_group(group), translate_f64) for group in CMPXF64_GROUPS) + fixtures.append((cmpx_class_group(kind="f16"), translate)) fixtures.extend((program, translate_int) for op in SHIFT64_OPS for program in shift64_programs(op).values()) fixtures.extend((region_body_program(body, approximate), translate) for _, body, _, approximate in REGION_BODY_FORMS) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 72a243015..cb9869577 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -2043,6 +2043,41 @@ def f64_operand(token, scalar, vector, pending, sample_dest, *, encoding, positi return low, high +def f64_comparison(i, op, tokens, encoding, scalar, vector, pending, sample_dest): + """HLSL word declarations and the predicate of a binary64 v_cmp or v_cmpx of `tokens` (op may be "class"). + + The predicates compare the raw (low, high) words with the cmp_f64 helpers and use no HLSL double; the caller + adds the helpers and checks the binary64 denormal entry state. + """ + if op == "class": + low, high = f64_operand(tokens[0], scalar, vector, pending, sample_dest, encoding=encoding, position=0, + allow_mods=False) + classes = tokens[1] + if encoding == "e32" and not re.fullmatch(r"v\d+", classes): + raise ValueError("VOPC e32 src1 must be a VGPR") + if re.fullmatch(r"-?\d+|0x[0-9a-f]{1,8}", classes): + bits = f"{int(classes, 0) & 0xffffffff}u" + elif re.fullmatch(r"[vs]\d+", classes): + bits = int_operand(classes, scalar, vector, pending, sample_dest, signed=False) + else: + raise ValueError("Unsupported class mask") + return [], f"(class64({low}, {high}) & {bits}) != 0u" + words = [f64_operand(t, scalar, vector, pending, sample_dest, encoding=encoding, position=n) + for n, t in enumerate(tokens)] + lines = [f" uint cmp{i}_{name} = {value};" for name, value in zip(("l0", "h0", "l1", "h1"), (*words[0], *words[1]))] + lines += [f" bool cmp{i}_o = num64(cmp{i}_l0, cmp{i}_h0) && num64(cmp{i}_l1, cmp{i}_h1);", + f" uint2 cmp{i}_a = key64(cmp{i}_l0, cmp{i}_h0);", + f" uint2 cmp{i}_b = key64(cmp{i}_l1, cmp{i}_h1);"] + keys = {"a": f"cmp{i}_a", "b": f"cmp{i}_b"} + if op in F64_RELATION: + expr = f"cmp{i}_o && {F64_RELATION[op].format(**keys)}" + elif op in F64_NEGATED: + expr = f"!(cmp{i}_o && {F64_RELATION[F64_NEGATED[op]].format(**keys)})" + else: + expr = {"o": f"cmp{i}_o", "u": f"!cmp{i}_o"}.get(op, COMPARE[op]) + return lines, expr + + def int64_comparison(i, op, kind, tokens, encoding, scalar, vector, pending, sample_dest): """HLSL word declarations and the predicate of a 64-bit integer v_cmp or v_cmpx of `tokens`.""" words = [int64_operand(t, scalar, vector, pending, sample_dest, signed=kind == "i64", @@ -2215,6 +2250,38 @@ def f16_cmp_operand(token, scalar, vector, pending, sample_dest, *, allow_mods, return expr +def f16_comparison(op, tokens, scalar, vector, pending, sample_dest, *, allow_mods): + """The predicate of a binary16 v_cmp or v_cmpx of `tokens`: ordered relations also require num16 of both.""" + values = [f16_cmp_operand(t, scalar, vector, pending, sample_dest, allow_mods=allow_mods, as_bits=False) + for t in tokens] + raw = [f16_cmp_operand(t, scalar, vector, pending, sample_dest, allow_mods=allow_mods, as_bits=True) + for t in tokens] + ordered = f"(num16({raw[0]}) && num16({raw[1]}))" + direct = {"lt": "lt", "eq": "eq", "le": "le", "gt": "gt", "lg": "lg", "ge": "ge"} + negated = {"nge": "ge", "nlg": "lg", "ngt": "gt", "nle": "le", "nlt": "lt", "neq": "eq"} + if op in direct: + return f"({ordered} && ({COMPARE[op].format(*values)}))" + if op in negated: + return f"!({ordered} && ({COMPARE[negated[op]].format(*values)}))" + if op == "o": + return ordered + if op == "u": + return f"!{ordered}" + return COMPARE[op] + + +def f16_class(value, classes, scalar, vector, pending, sample_dest, *, allow_mods): + """The predicate of a binary16 v_cmp_class or v_cmpx_class: the class of the low 16 bits of `value` in the mask.""" + if re.fullmatch(r"-?\d+|0x[0-9a-f]{1,8}", classes): + bits = f"{int(classes, 0) & 0xffffffff}u" + elif re.fullmatch(r"[vs]\d+", classes): + bits = int_operand(classes, scalar, vector, pending, sample_dest, signed=False) + else: + raise ValueError("Unsupported class mask") + operand = f16_cmp_operand(value, scalar, vector, pending, sample_dest, allow_mods=allow_mods, as_bits=True) + return f"(class16({operand}) & {bits}) != 0u" + + def parse_vop3p_f16(rest, arity): parts_ = rest.split(", ") if len(parts_) != arity: @@ -3201,15 +3268,20 @@ def match(pattern): scalar.masked = True scc = None elif m := match(rf"v_cmpx_(?:({'|'.join(COMPARE)})_f32|({'|'.join(INT_COMPARE)})_(i32|u32|i64|u64)" - rf"|(eq|ne|lt|le|gt|ge)_(i16|u16)|(class)_f32)_e32 ([^,]+), ([^,]+)"): + rf"|(eq|ne|lt|le|gt|ge)_(i16|u16)|(class)_f32" + rf"|({'|'.join(COMPARE)})_f16|(class)_f16" + rf"|({'|'.join(COMPARE)}|class)_f64)_e32 ([^,]+), ([^,]+)"): # A masked-if opened by a VOPC e32 compare that writes EXEC (issue #932). It must directly # follow `s_mov_b64 s[a:b], exec` of the known entry mask, so EXEC becomes the entry mask # intersected with the comparison, as after s_and_saveexec_b64. v_cmpx writes neither VCC nor # SCC, so both keep their tracked values; the region closes with s_mov_b64 or s_or_b64. # The integer forms compare as the v_cmp of the same width (gfx10 has no f/t forms at 16 bits). # v_cmpx_class_f32 tests the class of the raw binary32 encoding in src0 against the mask in VSRC1, - # as the e32 v_cmp_class_f32 does. - fop, iop, kind, op16, kind16, cls, src0, src1 = m.groups() + # as the e32 v_cmp_class_f32 does. The binary16 forms and v_cmpx_class_f16 read the low 16 bits + # of each source through the lowering of the e32 v_cmp_f16 and v_cmp_class_f16. The binary64 forms + # (and v_cmpx_class_f64) lower as the e32 v_cmp_*_f64 and need the same declared binary64 denormal + # entry state. + fop, iop, kind, op16, kind16, cls, hop, hcls, f64op, src0, src1 = m.groups() if op16 is not None: iop, kind = op16, kind16 previous = instructions[i - 1] if i else "" @@ -3220,11 +3292,24 @@ def match(pattern): or [scalar.get(r) for r in pair] != [("entry", 0), ("entry", 1)]): raise ValueError("Unsupported v_cmpx execution mask save") # VOPC e32 encodes VSRC1 as a VGPR (a VGPR pair at 64 bits) and carries no source modifiers. - vsrc1 = r"v\[\d+:\d+\]" if kind in ("i64", "u64") else r"v\d+" + wide = kind in ("i64", "u64") or f64op not in (None, "class") + vsrc1 = r"v\[\d+:\d+\]" if wide else r"v\d+" if not re.fullmatch(vsrc1, src1) or re.search(r"\||abs\(|neg\(|^-[vs]", src0): raise ValueError(f"Invalid VOPC e32 operands: {line}") if fop is not None: expr = f32_comparison(fop, [src0, src1], scalar, vector, pending, sample_dest) + elif hop is not None or hcls is not None: + if hcls is not None: + expr = f16_class(src0, src1, scalar, vector, pending, sample_dest, allow_mods=False) + else: + expr = f16_comparison(hop, [src0, src1], scalar, vector, pending, sample_dest, allow_mods=False) + elif f64op is not None: + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary64 denormal mode unknown at entry") + helpers.add("cmp_f64") + declarations, expr = f64_comparison(i, f64op, [src0, src1], "e32", scalar, vector, pending, + sample_dest) + lines.extend(declarations) elif cls is not None: operand = fp_operand(src0, scalar, vector, pending, sample_dest) bits = fp_operand(src1, scalar, vector, pending, sample_dest) @@ -4263,18 +4348,10 @@ def sample_coord(reg): regs = lane_mask(dst) if mask != "entry" or pending.intersection(regs): raise ValueError("Invalid comparison") - if re.fullmatch(r"-?\d+|0x[0-9a-f]{1,8}", classes): - bits = f"{int(classes, 0) & 0xffffffff}u" - elif re.fullmatch(r"[vs]\d+", classes): - bits = int_operand(classes, scalar, vector, pending, sample_dest, signed=False) - else: - raise ValueError("Unsupported class mask") - operand = f16_cmp_operand( - value, scalar, vector, pending, sample_dest, allow_mods=enc == "_e64", as_bits=True - ) + expr = f16_class(value, classes, scalar, vector, pending, sample_dest, allow_mods=enc == "_e64") for j, reg in enumerate(regs): scalar[reg] = ("condition", f"cmp{i}", j, len(regs)) - lines.append(f" bool cmp{i} = (class16({operand}) & {bits}) != 0u;") + lines.append(f" bool cmp{i} = {expr};") elif m := (match(r"v_(add|sub|subrev)_nc_u32(?:_e32|_e64)? (v\d+), ([^,\s]+), ([^,\s]+)") or match(r"v_(add|sub)_nc_i32 (v\d+), ([^,\s]+), ([^,\s]+)")): @@ -4469,27 +4546,7 @@ def sample_coord(reg): regs = lane_mask(dst) if mask != "entry" or pending.intersection(regs): raise ValueError("Invalid comparison") - values = [ - f16_cmp_operand(t, scalar, vector, pending, sample_dest, allow_mods=enc == "_e64", as_bits=False) - for t in tokens - ] - raw = [ - f16_cmp_operand(t, scalar, vector, pending, sample_dest, allow_mods=enc == "_e64", as_bits=True) - for t in tokens - ] - ordered = f"(num16({raw[0]}) && num16({raw[1]}))" - direct = {"lt": "lt", "eq": "eq", "le": "le", "gt": "gt", "lg": "lg", "ge": "ge"} - negated = {"nge": "ge", "nlg": "lg", "ngt": "gt", "nle": "le", "nlt": "lt", "neq": "eq"} - if op in direct: - expr = f"({ordered} && ({COMPARE[op].format(*values)}))" - elif op in negated: - expr = f"!({ordered} && ({COMPARE[negated[op]].format(*values)}))" - elif op == "o": - expr = ordered - elif op == "u": - expr = f"!{ordered}" - else: - expr = COMPARE[op] + expr = f16_comparison(op, tokens, scalar, vector, pending, sample_dest, allow_mods=enc == "_e64") for j, reg in enumerate(regs): scalar[reg] = ("condition", f"cmp{i}", j, len(regs)) lines.append(f" bool cmp{i} = {expr};") @@ -4554,35 +4611,9 @@ def sample_coord(reg): if mask != "entry" or pending.intersection(regs): raise ValueError("Invalid comparison") helpers.add("cmp_f64") - if op == "class": - low, high = f64_operand(tokens[0], scalar, vector, pending, sample_dest, encoding=enc, position=0, - allow_mods=False) - classes = tokens[1] - if enc == "e32" and not re.fullmatch(r"v\d+", classes): - raise ValueError("VOPC e32 src1 must be a VGPR") - if re.fullmatch(r"-?\d+|0x[0-9a-f]{1,8}", classes): - bits = f"{int(classes, 0) & 0xffffffff}u" - elif re.fullmatch(r"[vs]\d+", classes): - bits = int_operand(classes, scalar, vector, pending, sample_dest, signed=False) - else: - raise ValueError("Unsupported class mask") - lines.append(f" bool cmp{i} = (class64({low}, {high}) & {bits}) != 0u;") - else: - words = [f64_operand(t, scalar, vector, pending, sample_dest, encoding=enc, position=n) - for n, t in enumerate(tokens)] - for name, value in zip(("l0", "h0", "l1", "h1"), (*words[0], *words[1])): - lines.append(f" uint cmp{i}_{name} = {value};") - lines += [f" bool cmp{i}_o = num64(cmp{i}_l0, cmp{i}_h0) && num64(cmp{i}_l1, cmp{i}_h1);", - f" uint2 cmp{i}_a = key64(cmp{i}_l0, cmp{i}_h0);", - f" uint2 cmp{i}_b = key64(cmp{i}_l1, cmp{i}_h1);"] - keys = {"a": f"cmp{i}_a", "b": f"cmp{i}_b"} - if op in F64_RELATION: - expr = f"cmp{i}_o && {F64_RELATION[op].format(**keys)}" - elif op in F64_NEGATED: - expr = f"!(cmp{i}_o && {F64_RELATION[F64_NEGATED[op]].format(**keys)})" - else: - expr = {"o": f"cmp{i}_o", "u": f"!cmp{i}_o"}.get(op, COMPARE[op]) - lines.append(f" bool cmp{i} = {expr};") + declarations, expr = f64_comparison(i, op, tokens, enc, scalar, vector, pending, sample_dest) + lines.extend(declarations) + lines.append(f" bool cmp{i} = {expr};") for j, reg in enumerate(regs): scalar[reg] = ("condition", f"cmp{i}", j, len(regs)) elif m := match(rf"v_cmp_({'|'.join(COMPARE)})_f32_sdwa {LANE_MASK}, ([^,]+), ([^,]+) src0_sel:DWORD src1_sel:DWORD"): From 7dbe51617081949aabc9fe2c0ea880c0ab9fbb51 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:24:05 +0100 Subject: [PATCH 026/775] tests/startup_stream_depth: use correct guest vtable slots 9/10/14/8 for list/queue/fence --- tests/startup_stream_depth.cpp | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/tests/startup_stream_depth.cpp b/tests/startup_stream_depth.cpp index 0eb2af231..e91ee8b7a 100644 --- a/tests/startup_stream_depth.cpp +++ b/tests/startup_stream_depth.cpp @@ -163,16 +163,13 @@ int clear_depth_desktop(ID3D12Device* desktop, ID3D12Resource* depth_tex) int execute_guest_list(void* queue, void* list, void* fence, UINT64 fence_value) { - if (FAILED(static_cast(invoke(list, 10)))) return 50; + if (FAILED(static_cast(invoke(list, 9)))) return 50; void* lists[] = {list}; - invoke(queue, 11, 1, ptr_arg(lists)); - if (FAILED(static_cast(invoke(queue, 15, ptr_arg(fence), fence_value)))) return 51; - HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); - if (!ev) return 52; - const bool ok = SUCCEEDED(static_cast(invoke(fence, 10, fence_value, reinterpret_cast(ev)))) && - WaitForSingleObject(ev, 10000) == WAIT_OBJECT_0; - CloseHandle(ev); - return ok ? 0 : 53; + invoke(queue, 10, 1, ptr_arg(lists)); + if (FAILED(static_cast(invoke(queue, 14, ptr_arg(fence), fence_value)))) return 51; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < fence_value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) >= fence_value ? 0 : 53; } } // namespace From 49776ef626a69328530b793d8c0320f58a90c593 Mon Sep 17 00:00:00 2001 From: toddh <307535386+archielcqp-a11y@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:24:12 -0500 Subject: [PATCH 027/775] gpu: add reductions, prefixes and quad reads to wave64 emulation Extend src/wave64_emulate.hlsli with the 64-lane min, max, bit and, or, xor and count-bits reductions, the exclusive prefix sum and prefix count, and the four quad reads. The reductions and prefixes share Wave64Fold, which folds lanes 0..count-1 between the same two group barriers; Wave64ActiveSum now uses it too. Quads are lanes 4q..4q+3. wave64_emulate checks 1216 values per run (was 448) against the CPU reference. The skewed negative control now also makes the prefix sum inclusive and must be reported on exactly the 64 affine reads and 64 prefix sums. AI-assisted (Claude Code); reviewed and run locally. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 15 +++++----- src/wave64_emulate.hlsli | 44 +++++++++++++++++++++++++---- tests/wave64_emulate.cpp | 58 +++++++++++++++++++++++++++------------ tests/wave64_emulate.hlsl | 23 ++++++++++++---- 4 files changed, 104 insertions(+), 36 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 82c8b5706..720f386f8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6353,19 +6353,20 @@ On Windows 11 build 26200 at `1ccc326`, the in-box WARP (10.0.26100.9818) report ### Wave64 emulation with group-shared memory -`src/wave64_emulate.hlsli` gives a 64-thread group the results of 64-lane wave operations without wave intrinsics: `Wave64ReadLaneAt`, `Wave64ReadLaneFirst`, `Wave64ActiveSum` and `Wave64ActiveBallot`. Each lane (its `SV_GroupIndex`) writes its value to a group-shared slot, the group waits on a barrier, every lane reads the slots it needs, and a second barrier frees the slots for the next call. The result does not depend on the native wave width, so it holds on 32-lane NVIDIA waves, on WARP's 8 lanes, and under a forced `[WaveSize(64)]` on WARP 1.0.22, where `WaveReadLaneAt` misroutes. The fixture needs only `cs_6_0`. +`src/wave64_emulate.hlsli` gives a 64-thread group the results of 64-lane wave operations without wave intrinsics: `Wave64ReadLaneAt`, `Wave64ReadLaneFirst`, `Wave64ActiveBallot`, the reductions `Wave64ActiveSum`, `Wave64ActiveMin`, `Wave64ActiveMax`, `Wave64ActiveBitAnd`, `Wave64ActiveBitOr`, `Wave64ActiveBitXor` and `Wave64ActiveCountBits`, the exclusive prefixes `Wave64PrefixSum` and `Wave64PrefixCountBits` (lane 0 gets 0, as with `WavePrefixSum`), and the quad reads `Wave64QuadReadLaneAt`, `Wave64QuadReadAcrossX`, `Wave64QuadReadAcrossY` and `Wave64QuadReadAcrossDiagonal` (quad q is lanes 4q to 4q+3, the compute quad layout of SM 6.6). The reductions and prefixes share `Wave64Fold`, which folds lanes 0 to count-1; the prefix passes its own lane as the count, so the loop bound differs per lane while both barriers stay outside the loop. Each lane (its `SV_GroupIndex`) writes its value to a group-shared slot, the group waits on a barrier, every lane reads the slots it needs, and a second barrier frees the slots for the next call. The result does not depend on the native wave width, so it holds on 32-lane NVIDIA waves, on WARP's 8 lanes, and under a forced `[WaveSize(64)]` on WARP 1.0.22, where `WaveReadLaneAt` misroutes. The fixture needs only `cs_6_0`. -Limits: the group must be exactly 64 threads, and every call must be reached by all 64 threads in uniform control flow, because a group barrier inside divergent control flow is undefined. With all 64 lanes active, the first active lane is lane 0. Values are `uint`. Prefix, min/max, bitwise and quad operations are not provided. The `wave_shuffle` and `bvh_wave64` tests still measure the adapters' own wave operations and are unchanged. +Limits: the group must be exactly 64 threads, and every call must be reached by all 64 threads in uniform control flow, because a group barrier inside divergent control flow is undefined. With all 64 lanes active, the first active lane is lane 0. Values are `uint`, and min and max compare them unsigned. Signed and floating-point reductions, `WavePrefixProduct`, `WaveActiveAllEqual` and `WaveMatch` are not provided. The `wave_shuffle` and `bvh_wave64` tests still measure the adapters' own wave operations and are unchanged. -`wave64_emulate_` compares the affine, rotation and mirror reads of `wave_shuffle`, a first-lane read, a sum and a ballot (`t % 3 == 0`) on all 64 threads with a CPU reference, 448 values per run. It runs at the native width and, where SM 6.6 and the lane range allow it, at a forced width of 64. The negative control is a build whose affine read requests the next lane, and the test requires it to be reported on all 64 threads. +`wave64_emulate_` compares the affine, rotation and mirror reads of `wave_shuffle`, a first-lane read, the seven reductions, the two prefixes, a ballot and the four quad reads on all 64 threads with a CPU reference, 1,216 values per run. The predicate is `t % 3 == 0`, and the AND reduction reads each value with the bits of `0x0f0000f0` set, so its result is not trivially 0. It runs at the native width and, where SM 6.6 and the lane range allow it, at a forced width of 64. The negative control is a build whose affine read requests the next lane and whose prefix sum includes the lane's own value. The test requires exactly those 128 values to be reported, 64 affine reads and 64 prefix sums. -Measured on `31f9ebb` with this change, Windows 10 build 19045, debug layer enabled: +Measured on `eebc6c8` with the reductions, prefixes and quad reads, Windows 10 build 19045, debug layer enabled: | Adapter | Native width | Forced width 64 | Negative control | |---|---|---|---| -| WARP 1.0.22 (Agility SDK 1.620.2) | 0 of 448 wrong | 0 of 448 wrong; `wave_shuffle_warp` on the same adapter: 64 of 64 affine reads misrouted | 64 of 64 reported | -| WARP 10.0.19041 (in-box) | 0 of 448 wrong | Skipped, lane range 4..4 | 64 of 64 reported | -| NVIDIA GeForce RTX 3080 (32.0.15.9174) | 0 of 448 wrong | Skipped, lane range 32..32 | 64 of 64 reported | +| WARP 1.0.22 (Agility SDK 1.620.2), lane range 4..128 | 0 of 1,216 wrong | 0 of 1,216 wrong | 128 of 128 reported, none elsewhere | +| NVIDIA GeForce RTX 3080 (32.0.15.9174) | 0 of 1,216 wrong | Skipped, lane range 32..32 | 128 of 128 reported, none elsewhere | + +The first version (`31f9ebb`, 448 values) also passed on the in-box WARP 10.0.19041 (lane range 4..4, forced width skipped); that adapter was not rerun for this version. On WARP 1.0.22 at forced width 64, `wave_shuffle_warp` misroutes 64 of 64 of the adapter's own affine `WaveReadLaneAt` reads. ```powershell ctest --preset dev --no-tests=error -R '^wave64_emulate_' -V diff --git a/src/wave64_emulate.hlsli b/src/wave64_emulate.hlsli index 0bfa8b5a4..8ba7c9eb2 100644 --- a/src/wave64_emulate.hlsli +++ b/src/wave64_emulate.hlsli @@ -3,7 +3,7 @@ // NVIDIA's 32) and does not depend on WARP 1.0.22's forced-wave64 WaveReadLaneAt (issue #145). // Requirements: `lane` is SV_GroupIndex of a group of exactly 64 threads, and every call is reached by // all 64 threads in uniform control flow, because each call waits on group barriers. All 64 lanes are -// active, so the first active lane is lane 0. Values are uint. +// active, so the first active lane is lane 0. Values are uint; min and max compare them unsigned. groupshared uint g_wave64[64]; uint Wave64ReadLaneAt(uint value, uint lane, uint source) @@ -17,16 +17,50 @@ uint Wave64ReadLaneAt(uint value, uint lane, uint source) uint Wave64ReadLaneFirst(uint value, uint lane) { return Wave64ReadLaneAt(value, lane, 0); } -uint Wave64ActiveSum(uint value, uint lane) +// Quad operations: lanes 4q..4q+3 form quad q, as in the compute quad layout of SM 6.6. +uint Wave64QuadReadLaneAt(uint value, uint lane, uint quadLane) { return Wave64ReadLaneAt(value, lane, (lane & ~3u) | (quadLane & 3u)); } +uint Wave64QuadReadAcrossX(uint value, uint lane) { return Wave64ReadLaneAt(value, lane, lane ^ 1u); } +uint Wave64QuadReadAcrossY(uint value, uint lane) { return Wave64ReadLaneAt(value, lane, lane ^ 2u); } +uint Wave64QuadReadAcrossDiagonal(uint value, uint lane) { return Wave64ReadLaneAt(value, lane, lane ^ 3u); } + +#define WAVE64_SUM 0u +#define WAVE64_MIN 1u +#define WAVE64_MAX 2u +#define WAVE64_AND 3u +#define WAVE64_OR 4u +#define WAVE64_XOR 5u + +// Folds the values of lanes 0..count-1 with `op`; count 64 gives the whole wave, count `lane` the exclusive +// prefix. The loop bound may differ per lane; the barriers stay outside it. +uint Wave64Fold(uint value, uint lane, uint op, uint count) { g_wave64[lane] = value; GroupMemoryBarrierWithGroupSync(); - uint sum = 0; - for (uint i = 0; i < 64; ++i) sum += g_wave64[i]; + uint result = (op == WAVE64_MIN || op == WAVE64_AND) ? 0xffffffffu : 0u; + for (uint i = 0; i < count; ++i) { + uint v = g_wave64[i]; + if (op == WAVE64_SUM) result += v; + else if (op == WAVE64_MIN) result = min(result, v); + else if (op == WAVE64_MAX) result = max(result, v); + else if (op == WAVE64_AND) result &= v; + else if (op == WAVE64_OR) result |= v; + else result ^= v; + } GroupMemoryBarrierWithGroupSync(); - return sum; + return result; } +uint Wave64ActiveSum(uint value, uint lane) { return Wave64Fold(value, lane, WAVE64_SUM, 64); } +uint Wave64ActiveMin(uint value, uint lane) { return Wave64Fold(value, lane, WAVE64_MIN, 64); } +uint Wave64ActiveMax(uint value, uint lane) { return Wave64Fold(value, lane, WAVE64_MAX, 64); } +uint Wave64ActiveBitAnd(uint value, uint lane) { return Wave64Fold(value, lane, WAVE64_AND, 64); } +uint Wave64ActiveBitOr(uint value, uint lane) { return Wave64Fold(value, lane, WAVE64_OR, 64); } +uint Wave64ActiveBitXor(uint value, uint lane) { return Wave64Fold(value, lane, WAVE64_XOR, 64); } +uint Wave64ActiveCountBits(bool predicate, uint lane) { return Wave64Fold(predicate ? 1u : 0u, lane, WAVE64_SUM, 64); } +// Exclusive prefixes, as WavePrefixSum and WavePrefixCountBits: lane 0 gets 0. +uint Wave64PrefixSum(uint value, uint lane) { return Wave64Fold(value, lane, WAVE64_SUM, lane); } +uint Wave64PrefixCountBits(bool predicate, uint lane) { return Wave64Fold(predicate ? 1u : 0u, lane, WAVE64_SUM, lane); } + // Lanes 0..31 in .x and 32..63 in .y, like WaveActiveBallot's first two words. uint2 Wave64ActiveBallot(bool predicate, uint lane) { diff --git a/tests/wave64_emulate.cpp b/tests/wave64_emulate.cpp index 2d8b645df..b13199aa5 100644 --- a/tests/wave64_emulate.cpp +++ b/tests/wave64_emulate.cpp @@ -1,22 +1,26 @@ // Wave64 emulation (src/wave64_emulate.hlsli) against a CPU reference. The fixture runs at the adapter's // native width and, where SM 6.6 and the lane range allow it, at a forced width of 64, the setting in // which WARP 1.0.22's own WaveReadLaneAt misroutes (wave_shuffle, issue #145). The skewed build is the -// negative control and must be reported on every affine read. +// negative control and must be reported on every affine read and prefix sum, and nowhere else. #include "bvh_fixture.h" #include "Wave64Emulate.h" #include "Wave64Emulate64.h" #include "Wave64EmulateSkew.h" -#include using namespace bvh_fixture; namespace { -constexpr Word threads = 64, fields = 8, checked = 7; +constexpr Word threads = 64, fields = 24, checked = 19; +constexpr Word affine_field = 0, prefix_field = 7; Word value(Word t) { return t * 2654435761u + 12345u; } -// Returns {wrong values, wrong affine reads}. -std::pair run_variant(ID3D12Device* device, const char* label, D3D12_SHADER_BYTECODE code) +struct Result { + unsigned wrong, affine, prefix; +}; + +// Returns the wrong values, and the wrong affine reads and prefix sums of the fields the skewed build changes. +Result run_variant(ID3D12Device* device, const char* label, D3D12_SHADER_BYTECODE code) { constexpr UINT bytes = threads * fields * sizeof(Word); Kernel shader(device, code); @@ -34,24 +38,41 @@ std::pair run_variant(ID3D12Device* device, const char* labe cmd.submit_and_wait(device); const auto r = read(back.Get(), threads * fields); - Word sum = 0, ballot[2] = {}; + Word sum = 0, ballot[2] = {}, low = ~0u, high = 0, all = ~0u, any = 0, parity = 0, count = 0; + Word prefix[threads], prefix_count[threads]; for (Word t = 0; t < threads; ++t) { - sum += value(t); - if (t % 3 == 0) ballot[t / 32] |= 1u << (t % 32); + prefix[t] = sum; + prefix_count[t] = count; + const Word v = value(t); + sum += v; + low = v < low ? v : low; + high = v > high ? v : high; + all &= v | 0x0f0000f0u; + any |= v; + parity ^= v; + if (t % 3 == 0) { + ballot[t / 32] |= 1u << (t % 32); + ++count; + } } - unsigned wrong = 0, affine = 0; + Result result{}; for (Word t = 0; t < threads; ++t) { const Word* rec = r.data() + t * fields; const Word expected[checked] = {value((t * 7 + 3) % 64), value((t + 1) % 64), value(63 - t), value(0), - sum, ballot[0], ballot[1]}; + sum, ballot[0], ballot[1], prefix[t], + low, high, all, any, + parity, count, prefix_count[t], value((t & ~3u) | 2u), + value(t ^ 1u), value(t ^ 2u), value(t ^ 3u)}; for (Word i = 0; i < checked; ++i) if (rec[i] != expected[i]) { - ++wrong; - if (i == 0) ++affine; + ++result.wrong; + if (i == affine_field) ++result.affine; + if (i == prefix_field) ++result.prefix; } } - std::printf("wave64_emulate %s wrong=%u of %u affine_wrong=%u\n", label, wrong, threads * checked, affine); - return {wrong, affine}; + std::printf("wave64_emulate %s wrong=%u of %u affine_wrong=%u prefix_wrong=%u\n", label, result.wrong, + threads * checked, result.affine, result.prefix); + return result; } } @@ -64,14 +85,15 @@ void check_wave64_emulate(ID3D12Device* device) // The native build has no wave intrinsics, so it cannot observe its width; report the adapter's range. std::printf("wave64_emulate native_lane_range=%u..%u\n", caps.WaveLaneCountMin, caps.WaveLaneCountMax); - unsigned errors = run_variant(device, "native", {Wave64Emulate, sizeof(Wave64Emulate)}).first; + unsigned errors = run_variant(device, "native", {Wave64Emulate, sizeof(Wave64Emulate)}).wrong; const auto skew = run_variant(device, "skew", {Wave64EmulateSkew, sizeof(Wave64EmulateSkew)}); - if (skew.first != threads || skew.second != threads) - throw std::runtime_error("Negative control: the skewed affine read was not reported on every thread"); + if (skew.wrong != 2 * threads || skew.affine != threads || skew.prefix != threads) + throw std::runtime_error("Negative control: the skewed affine read and inclusive prefix sum were not " + "reported on every thread, and only there"); if (caps.WaveOps && model.HighestShaderModel >= D3D_SHADER_MODEL_6_6 && caps.WaveLaneCountMin <= 64 && caps.WaveLaneCountMax >= 64) - errors += run_variant(device, "forced64", {Wave64Emulate64, sizeof(Wave64Emulate64)}).first; + errors += run_variant(device, "forced64", {Wave64Emulate64, sizeof(Wave64Emulate64)}).wrong; else std::printf("wave64_emulate forced width=64 skipped\n"); if (errors) throw std::runtime_error("Wave64 emulation differs from the CPU reference"); diff --git a/tests/wave64_emulate.hlsl b/tests/wave64_emulate.hlsl index a17022d89..dc1f8b273 100644 --- a/tests/wave64_emulate.hlsl +++ b/tests/wave64_emulate.hlsl @@ -1,7 +1,8 @@ // Wave64 emulation (src/wave64_emulate.hlsli) over one 64-thread group: the reads of -// tests/wave_shuffle.hlsl at a width of 64 whatever the device's waves are, plus a first-lane read, a sum -// and a ballot. WAVE_SIZE forces the native width (SM 6.6). SKEW is the negative control: the affine -// read asks for the next lane, which the CPU check must report on every thread. +// tests/wave_shuffle.hlsl at a width of 64 whatever the device's waves are, plus a first-lane read, the +// reductions, the exclusive prefixes, a ballot and the quad reads. WAVE_SIZE forces the native width (SM 6.6). +// SKEW is the negative control: the affine read asks for the next lane and the prefix sum includes the +// lane's own value, which the CPU check must report on every thread. #include "wave64_emulate.hlsli" RWByteAddressBuffer output : register(u0); @@ -14,16 +15,26 @@ uint Value(uint t) { return t * 2654435761u + 12345u; } void Emulate(uint t : SV_GroupIndex) { uint v = Value(t); + bool p = t % 3 == 0; #ifdef SKEW uint gathered = Wave64ReadLaneAt(v, t, (t * 7 + 3) % 64 + 1); + uint prefix = Wave64Fold(v, t, WAVE64_SUM, t + 1); #else uint gathered = Wave64ReadLaneAt(v, t, (t * 7 + 3) % 64); + uint prefix = Wave64PrefixSum(v, t); #endif uint rotated = Wave64ReadLaneAt(v, t, (t + 1) % 64); uint mirrored = Wave64ReadLaneAt(v, t, 63 - t); uint first = Wave64ReadLaneFirst(v, t); uint sum = Wave64ActiveSum(v, t); - uint2 ballot = Wave64ActiveBallot(t % 3 == 0, t); - output.Store4(t * 32, uint4(gathered, rotated, mirrored, first)); - output.Store4(t * 32 + 16, uint4(sum, ballot, 0)); + uint2 ballot = Wave64ActiveBallot(p, t); + output.Store4(t * 96, uint4(gathered, rotated, mirrored, first)); + output.Store4(t * 96 + 16, uint4(sum, ballot, prefix)); + // The AND operand keeps the bits of 0x0f0000f0 set in every lane, so the reduction is not trivially 0. + output.Store4(t * 96 + 32, uint4(Wave64ActiveMin(v, t), Wave64ActiveMax(v, t), + Wave64ActiveBitAnd(v | 0x0f0000f0u, t), Wave64ActiveBitOr(v, t))); + output.Store4(t * 96 + 48, uint4(Wave64ActiveBitXor(v, t), Wave64ActiveCountBits(p, t), + Wave64PrefixCountBits(p, t), Wave64QuadReadLaneAt(v, t, 2))); + output.Store4(t * 96 + 64, uint4(Wave64QuadReadAcrossX(v, t), Wave64QuadReadAcrossY(v, t), + Wave64QuadReadAcrossDiagonal(v, t), 0)); } From bb4272f5d4e5837a089925805daf9e085e844f0a Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:25:07 +0100 Subject: [PATCH 028/775] runtime: read a persisted blob through async save slots 21 and 22 Slots 21 and 22 snapshot committed blobs through the system XAsync service and pack them into the caller's buffer. A source-built Windows ctest covers the callback, the bytes, a missing blob, a short buffer, and overlap. Fixes #1355 --- CMakeLists.txt | 9 + docs/startup-runtime.md | 8 +- src/startup_stubs/runtime_proxy.cpp | 194 ++++++++++- src/startup_stubs/save_blob_pack.h | 62 ++++ src/startup_stubs/save_store.h | 5 + tests/startup_gamesave_read_async.cpp | 374 +++++++++++++++++++++ tests/startup_gamesave_read_async_check.py | 9 + 7 files changed, 652 insertions(+), 9 deletions(-) create mode 100644 src/startup_stubs/save_blob_pack.h create mode 100644 tests/startup_gamesave_read_async.cpp create mode 100644 tests/startup_gamesave_read_async_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1c2e79002..8d2c29bc9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -386,6 +386,9 @@ add_test(NAME startup_gamesave_lock_errors COMMAND startup_gamesave_lock_errors) add_executable(startup_gamesave_submit tests/startup_gamesave_submit.cpp) target_include_directories(startup_gamesave_submit PRIVATE src) target_compile_features(startup_gamesave_submit PRIVATE cxx_std_17) +add_executable(startup_gamesave_read_async tests/startup_gamesave_read_async.cpp) +target_include_directories(startup_gamesave_read_async PRIVATE src) +target_compile_features(startup_gamesave_read_async PRIVATE cxx_std_17) # Input for the launcher containment check (docs/startup-runtime.md): writes known bytes to both # streams and the trap log, reports a known exit code, or holds memory, spawns a child or stays @@ -1282,6 +1285,12 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gamesave_submit_${scheduler} PROPERTIES TIMEOUT 30) endforeach() set_tests_properties(startup_gamesave_submit_system PROPERTIES SKIP_RETURN_CODE 77) + foreach(scheduler IN ITEMS controlled system) + add_test(NAME startup_gamesave_read_async_${scheduler} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gamesave_read_async_check.py" "$" ${scheduler}) + set_tests_properties(startup_gamesave_read_async_${scheduler} PROPERTIES TIMEOUT 30) + endforeach() + set_tests_properties(startup_gamesave_read_async_system PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME startup_stubs COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stub_check.py" "$" "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs" "$" "$" "$" diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index efff6ec2f..1ff5469fa 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -233,8 +233,8 @@ can then hold some blobs of the new generation and some of the old one, with `.x The slot numbers and argument layouts follow the public header order and stay a hypothesis. Persisted: create container (16), delete container (10, 11), create and close update (23, 24), blob write and delete staged in an update (25, 26) and published by submit (27, 28 with its result in 29). -Not yet persisted, because their argument layout is not established: blob reads (20 to 22) still -report no blob, and the enumerations and queries (12 to 15, 18, 19) still report nothing. +Asynchronous read (21, with its result in 22) returns committed blobs. Slot 20 still reports no blob. +The enumerations and queries (12 to 15, 18, 19) still report nothing. `ctest --preset dev --no-tests=error -R '^startup_gamesave_persist$' -V` checks the storage code the slots call, not the slots: it writes in one process and reads in a second, including a close without submit, a failing second action, a second process that sees only committed state, and a redirected @@ -252,6 +252,10 @@ Slot 28 first asks the Windows gaming runtime to accept the caller's async block `ctest --preset dev --no-tests=error -R '^startup_gamesave_submit_'` checks denied starts and retries, two overlapping blocks and completion that reads the file and slot 29 before slot 28 returns. The system variant uses the installed Windows gaming runtime with an immediate work/completion queue. It reports a capability skip when the runtime or queue is unavailable. +Slot 21 reserves the caller's async block on that same XAsync service, with its own operation identity (`local XGameSaveReadBlobData`). If the service rejects the block, slot 21 returns before it reads. Once the block is accepted, it snapshots the named blobs through `read_blobs` (one shared file lock for the set), packs them, and completes with the status and the number of bytes slot 22 needs. It does not use the user service, and no save lock is held across `XAsyncComplete`. The packed bytes are an array of 24-byte records, payload pointer at offset 16, then each name, a NUL and the payload. Slot 22 copies that into the caller's buffer and reports the count. A short buffer returns `0x80830007` and a missing blob returns `0x80830008`; neither writes the caller's count or bytes. A busy snapshot, and any other storage failure, uses the same status as submit (`0x80004005`); a bad name is `0x80070057`. [XGameSaveReadBlobDataResult](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgamesave/functions/xgamesavereadblobdataresult) + +`ctest --preset dev --no-tests=error -R '^startup_gamesave_read_async_'` commits two blobs in one process and reads them in a second through slots 21 and 22. It checks the completion callback, the required size, the count and the exact bytes, a missing blob, a short buffer that leaves the output unchanged, and two overlapping reads. The controlled fixture always runs. The system variant uses an immediate Windows gaming runtime queue and skips only when that runtime is unavailable. + ## Findings These are measured on one executable; treat them as hypotheses for others. diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 4817215a2..cf6de0df4 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -9,14 +9,17 @@ // X2W_FAKE_USER=1 additionally answers the user API for one local user (see fake_user below). #include "startup_stubs/api_trace.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/save_blob_pack.h" #include "startup_stubs/save_store.h" #include #include #include #include +#include #include #include +#include namespace { using u64 = std::uint64_t; @@ -360,11 +363,11 @@ bool user_call(int slot, u64* args, u64* result) // ---- local game saves ----------------------------------------------------------------------- // Slot numbers follow the order of the public XGameSave.h (hypothesis, checked against the logged // argument shapes). Containers and blob writes are kept on disk (save_store.h, below -// storage_path()/x2w-gamesave); enumerations and reads still report nothing and the calls whose -// argument layout is not known are accepted and dropped. Asynchronous calls are completed by starting the real -// "add default user silently" operation on the caller's async block: it fails quickly inside the -// runtime and runs the caller's completion callback on its task queue; the matching Result call is -// then answered here. +// storage_path()/x2w-gamesave). Enumerations still report nothing, and the synchronous read (20) +// still reports no blob. Slots 21 and 22 read through the system XAsync service (see async_read). +// The other asynchronous calls are completed by starting the real "add default user silently" +// operation on the caller's async block: it fails quickly inside the runtime and runs the caller's +// completion callback on its task queue; the matching Result call is then answered here. constexpr u64 save_provider_handle = 0x58325753'00000001ull, save_container_handle = 0x58325743'00000001ull, save_update_handle = 0x58325755'50000001ull; // Container and update handles keep their fixed base; the low bits count from 1 and index these tables. @@ -471,6 +474,183 @@ u64 async_submit(int slot, u64 update, u64 block) reinterpret_cast(methods[10])(service, async, status, 0); return S_OK; } + +// XGameSaveReadBlobDataAsync / Result. Same XAsync service as submit, different identity, so a +// read block is not a submit block. Begin is attempted before any read: a rejection leaves the +// store untouched. The snapshot is packed only after acceptance. Complete can run the caller's +// callback before it returns, so no save lock is held across it. A failed read completes with no +// payload (the runtime then drops the context); the bytes are copied into the caller's buffer only +// when slot 22 asks, and only if that buffer is large enough. +constexpr char read_identity[] = "local XGameSaveReadBlobData"; +constexpr u64 small_buffer = 0x80830007; +struct AsyncProviderData { + void* async; + std::size_t buffer_size; + void* buffer; + void* context; +}; +static_assert(sizeof(AsyncProviderData) == 32 && offsetof(AsyncProviderData, context) == 24, "XAsyncProviderData"); +struct ReadAsync { + void* block = nullptr; + std::uint32_t count = 0; + std::size_t bytes = 0; + std::vector pieces; +}; +struct ReadRecord { void* block; std::uint32_t count; std::size_t bytes; }; +std::vector read_records; // accepted reads whose payload is still outstanding +SRWLOCK read_records_lock = SRWLOCK_INIT; +void remember_read(const ReadAsync& state) +{ + AcquireSRWLockExclusive(&read_records_lock); + struct Unlock { ~Unlock() { ReleaseSRWLockExclusive(&read_records_lock); } } unlock; + read_records.push_back({state.block, state.count, state.bytes}); +} +void forget_read(void* block) +{ + AcquireSRWLockExclusive(&read_records_lock); + struct Unlock { ~Unlock() { ReleaseSRWLockExclusive(&read_records_lock); } } unlock; + for (std::size_t i = 0; i < read_records.size(); ++i) + if (read_records[i].block == block) { + read_records.erase(read_records.begin() + static_cast(i)); + break; + } +} +bool pending_read(void* block, std::uint32_t& count, std::size_t& bytes) +{ + AcquireSRWLockShared(&read_records_lock); + struct Unlock { ~Unlock() { ReleaseSRWLockShared(&read_records_lock); } } unlock; + for (const ReadRecord& record : read_records) + if (record.block == block) { + count = record.count; + bytes = record.bytes; + return true; + } + return false; +} +HRESULT WINAPI read_provider(unsigned op, const void* raw) +{ + if (op == 0) return S_OK; // Begin: the read runs after XAsyncBegin accepts the block + if (!raw) return S_OK; + const auto* data = static_cast(raw); + auto* state = static_cast(data->context); + if (op == 2 && state && data->buffer && state->bytes <= data->buffer_size) + x2w_save_pack::write(state->pieces, data->buffer); // GetResult + if (op == 4 && state) { // Cleanup, including the runtime's cleanup of a failed read + forget_read(state->block); + delete state; + } + return S_OK; +} +// Names and bytes of one accepted read. The save lock is not held on return. +u64 snapshot_read(ReadAsync& state, u64 container, u64 names_pointer, std::uint32_t count) +{ + std::string container_name; + { + AcquireSRWLockShared(&save_lock); + struct Unlock { ~Unlock() { ReleaseSRWLockShared(&save_lock); } } unlock; + if (container >= save_container_handle && container - save_container_handle < max_save_handles) + container_name = save_table.container_name(static_cast(container - save_container_handle)); + } + if (container_name.empty()) return e_invalidarg; + if (count > SIZE_MAX / sizeof(const char*)) return e_invalidarg; + if (count && x2w_local::probe_readable(static_cast(names_pointer), sizeof(const char*) * count) != sizeof(const char*) * count) + return e_invalidarg; + const auto* names = reinterpret_cast(names_pointer); + std::vector wanted; + wanted.reserve(count); + for (std::uint32_t i = 0; i < count; ++i) { + std::string name; + if (!names[i] || !read_save_name(reinterpret_cast(names[i]), name) || !x2w_save::valid_name(name)) + return e_invalidarg; + wanted.push_back(std::move(name)); + } + std::vector> data; + const x2w_save::Status status = save_store().read_blobs(container_name, wanted, data); + if (status != x2w_save::Status::ok) return save_status(status); + if (data.size() != wanted.size() || data.size() > 0xffffffffu) return e_fail; + state.pieces.resize(data.size()); + for (std::size_t i = 0; i < data.size(); ++i) { + state.pieces[i].name = std::move(wanted[i]); + state.pieces[i].bytes = std::move(data[i]); + } + state.count = static_cast(state.pieces.size()); + if (!x2w_save_pack::bytes_needed(state.pieces, state.bytes)) return e_fail; + return 0; +} +u64 async_read(int slot, u64 container, u64 names, u64 count_or_size, u64 block_or_buffer, u64 count_pointer) +{ + if (!real_query) return e_fail; + void* service = nullptr; + const auto query = real_query(&submit_async_family, &submit_async_family, &service); + if (FAILED(query)) return static_cast(query); + if (!service) return e_fail; + auto** methods = *static_cast(service); + struct ApiRef { + void* object; + ULONG (WINAPI* release)(void*); + ~ApiRef() { release(object); } + } api{service, reinterpret_cast(methods[2])}; + if (slot == 22) { + auto* async = reinterpret_cast(container); // XGameSaveReadBlobDataResult(async, size, data, &count) + if (!async) return e_fail; + const auto out = [](u64 pointer, std::size_t bytes) { + return pointer && x2w_local::writable(reinterpret_cast(pointer), bytes); + }; + std::uint32_t count = 0; + std::size_t bytes = 0; + if (pending_read(async, count, bytes)) { + // A short or unusable buffer must not consume the result or change the caller's memory. + if (count_or_size < bytes) return small_buffer; + if (!out(count_pointer, sizeof(std::uint32_t)) || !out(block_or_buffer, bytes) || + block_or_buffer % alignof(x2w_save_pack::Blob)) return e_invalidarg; + using Result = HRESULT(WINAPI*)(void*, void*, const void*, size_t, void*, size_t*); + const auto hr = reinterpret_cast(methods[11])( + service, async, read_identity, static_cast(count_or_size), + reinterpret_cast(block_or_buffer), nullptr); + if (FAILED(hr)) return static_cast(hr); + *reinterpret_cast(count_pointer) = count; + return 0; + } + // No payload was kept: a missing blob or other failure, or a read of no blobs. The caller's + // buffer is not passed through, so a failure cannot change it. A success with no blobs + // reports a count of zero. + using Result = HRESULT(WINAPI*)(void*, void*, const void*, size_t, void*, size_t*); + const auto hr = reinterpret_cast(methods[11])(service, async, read_identity, 0, nullptr, nullptr); + if (FAILED(hr)) return static_cast(hr); + if (!out(count_pointer, sizeof(std::uint32_t))) return e_invalidarg; + *reinterpret_cast(count_pointer) = 0; + return 0; + } + auto* async = reinterpret_cast(block_or_buffer); + if (!async) return e_fail; + auto* state = new (std::nothrow) ReadAsync; + if (!state) return e_outofmemory; + using Begin = HRESULT(WINAPI*)(void*, void*, void*, const void*, const char*, decltype(&read_provider)); + const auto begun = reinterpret_cast(methods[7])(service, async, state, read_identity, read_identity, read_provider); + if (FAILED(begun)) { + delete state; // rejection: the runtime has not taken the context, and nothing was read + return static_cast(begun); + } + using Complete = void(WINAPI*)(void*, void*, HRESULT, size_t); + const auto complete = reinterpret_cast(methods[10]); + try { + state->block = async; + const u64 status = snapshot_read(*state, container, names, static_cast(count_or_size)); + if (status) { + complete(service, async, static_cast(status), 0); // no payload; context is released by Cleanup + return S_OK; + } + if (state->bytes) remember_read(*state); + complete(service, async, S_OK, state->bytes); + return S_OK; + } catch (const std::bad_alloc&) { + complete(service, async, static_cast(e_outofmemory), 0); + return S_OK; + } catch (const std::filesystem::filesystem_error&) { + complete(service, async, static_cast(e_fail), 0); + return S_OK; + } +} u64 complete_async(u64 async_block) { Proxy* user = user_provider >= 0 ? proxies[user_provider] : nullptr; @@ -540,10 +720,10 @@ bool save_call(int slot, u64* args, u64* result) *result = blob_not_found; return true; case 21: // XGameSaveReadBlobDataAsync(container, names, count, async) - *result = complete_async(args[3]); + *result = async_read(slot, args[0], args[1], args[2], args[3], 0); return true; case 22: // XGameSaveReadBlobDataResult(async, size, data, &count) - *result = blob_not_found; + *result = async_read(slot, args[0], 0, args[1], args[2], args[3]); return true; case 23: { // XGameSaveCreateUpdate(container, display name, &update) u64 handle = 0; diff --git a/src/startup_stubs/save_blob_pack.h b/src/startup_stubs/save_blob_pack.h new file mode 100644 index 000000000..14e04c9c2 --- /dev/null +++ b/src/startup_stubs/save_blob_pack.h @@ -0,0 +1,62 @@ +// Experimental (docs/startup-runtime.md): the caller-buffer layout of an XGameSave blob read. +// One 24-byte record per blob (payload pointer at offset 16), then each name, a NUL and the +// payload. The records point into that same buffer. Synchronous and asynchronous reads share this. +#pragma once + +#include +#include +#include +#include +#include + +namespace x2w_save_pack { + +struct BlobInfo { + const char* name; + std::uint32_t size; +}; +struct Blob { + BlobInfo info; + unsigned char* data; +}; +static_assert(sizeof(Blob) == 24 && offsetof(Blob, data) == 16, "XGameSaveBlob layout"); + +struct Piece { + std::string name; + std::vector bytes; +}; + +// False when the byte count does not fit in size_t. out is unchanged then. +inline bool bytes_needed(const std::vector& pieces, std::size_t& out) +{ + if (pieces.size() > SIZE_MAX / sizeof(Blob)) return false; + std::size_t bytes = pieces.size() * sizeof(Blob); + for (const Piece& piece : pieces) { + if (piece.name.size() == SIZE_MAX) return false; + const std::size_t extra = piece.name.size() + 1 + piece.bytes.size(); + if (extra < piece.name.size() || extra > SIZE_MAX - bytes) return false; + bytes += extra; + } + out = bytes; + return true; +} + +// dest has room for bytes_needed. Pointers in the records address dest itself. +inline void write(const std::vector& pieces, void* dest) +{ + auto* records = static_cast(dest); + auto* cursor = reinterpret_cast(records + pieces.size()); + for (std::size_t i = 0; i < pieces.size(); ++i) { + const Piece& piece = pieces[i]; + auto* name = reinterpret_cast(cursor); + if (!piece.name.empty()) std::memcpy(cursor, piece.name.data(), piece.name.size()); + cursor[piece.name.size()] = 0; + cursor += piece.name.size() + 1; + records[i].info = {name, static_cast(piece.bytes.size())}; + records[i].data = cursor; + if (!piece.bytes.empty()) std::memcpy(cursor, piece.bytes.data(), piece.bytes.size()); + cursor += piece.bytes.size(); + } +} + +} \ No newline at end of file diff --git a/src/startup_stubs/save_store.h b/src/startup_stubs/save_store.h index dfa00a023..1a4fdf09a 100644 --- a/src/startup_stubs/save_store.h +++ b/src/startup_stubs/save_store.h @@ -162,6 +162,11 @@ class ContainerTable { { return update < capacity && updates_[update] ? names_[updates_[update] - 1] : std::string(); } + // Name of an open container, or empty. The caller holds the lock. + std::string container_name(std::size_t index) const + { + return index < capacity && refs_[index] > 0 ? names_[index] : std::string(); + } std::size_t in_use() const { std::size_t used = 0; diff --git a/tests/startup_gamesave_read_async.cpp b/tests/startup_gamesave_read_async.cpp new file mode 100644 index 000000000..27d8fad89 --- /dev/null +++ b/tests/startup_gamesave_read_async.cpp @@ -0,0 +1,374 @@ +// A blob committed in one process is read in a second through slots 21 and 22. +// The controlled XAsync stand-in can reject Begin and hold one block open. The system +// variant uses the installed gaming runtime and an immediate queue, and exits 77 when +// that runtime cannot be loaded. +#include "../src/startup_stubs/runtime_proxy.cpp" + +#include +#include +#include +#include +#include + +namespace { +using Provider = decltype(&read_provider); +struct Block { + void* queue{}; + void* context{}; + void (WINAPI* callback)(Block*){}; + unsigned char internal[32]{}; +}; +struct ProviderData { + void* async; + std::size_t buffer_size; + void* buffer; + void* context; +}; +struct Operations { void* methods[12]{}; } operations; +void** api = operations.methods; +bool refuse = false; +struct Operation { + Block* block{}; + const void* id{}; + void* context{}; + Provider provider{}; + HRESULT result{E_PENDING}; + std::size_t bytes{}; +}; +std::array pending; +std::mutex pending_lock; +std::condition_variable progress; +Block* paused_block = nullptr; +bool entered = false; + +ULONG WINAPI drop(void*) { return 1; } +HRESULT WINAPI begin(void*, Block* block, void* context, const void* id, const char*, Provider provider) +{ + if (id && std::strcmp(static_cast(id), "local XGameSaveSubmitUpdate") == 0) return E_INVALIDARG; + std::unique_lock lock(pending_lock); + if (refuse) return E_ACCESSDENIED; + for (const auto& op : pending) + if (op.block == block) return E_INVALIDARG; + for (auto& op : pending) + if (!op.block) { + op = {block, id, context, provider, E_PENDING, 0}; + if (block == paused_block) { + entered = true; + progress.notify_one(); + progress.wait(lock, [] { return paused_block == nullptr; }); + } + lock.unlock(); + return provider(0, nullptr); + } + return E_OUTOFMEMORY; +} +void WINAPI complete(void*, Block* block, HRESULT status, std::size_t bytes) +{ + Provider provider{}; + void* context{}; + bool cleanup = false; + { + const std::lock_guard lock(pending_lock); + for (auto& op : pending) + if (op.block == block) { + op.result = status; + op.bytes = bytes; + if (FAILED(status) || bytes == 0) { + cleanup = true; + provider = op.provider; + context = op.context; + op.context = nullptr; + } + break; + } + } + if (block->callback) block->callback(block); + if (cleanup && provider && context) { + const ProviderData data{block, 0, nullptr, context}; + provider(4, &data); + } +} +HRESULT WINAPI get_result_size(void*, Block* block, std::size_t* out) +{ + const std::lock_guard lock(pending_lock); + for (const auto& op : pending) + if (op.block == block) { + if (out) *out = FAILED(op.result) ? 0 : op.bytes; + return op.result; + } + return E_INVALIDARG; +} +HRESULT WINAPI get_result(void*, Block* block, const void* id, std::size_t size, void* buffer, std::size_t* used) +{ + Provider provider{}; + void* context{}; + HRESULT status = E_INVALIDARG; + std::size_t bytes = 0; + { + const std::lock_guard lock(pending_lock); + for (auto& op : pending) + if (op.block == block) { + if (op.id != id) return E_INVALIDARG; + status = op.result; + if (FAILED(status) || op.bytes == 0) return status; + if (!op.context) return E_INVALIDARG; + if (!buffer || size < op.bytes) { + provider = op.provider; + context = op.context; + op.context = nullptr; + status = E_NOT_SUFFICIENT_BUFFER; + break; + } + provider = op.provider; + context = op.context; + bytes = op.bytes; + op.context = nullptr; + break; + } + if (!provider) return status; + } + const ProviderData data{block, size, buffer, context}; + if (status != E_NOT_SUFFICIENT_BUFFER) { + const HRESULT produced = provider(2, &data); + if (FAILED(produced)) status = produced; + else if (used) *used = bytes; + } + provider(4, &data); + return status; +} +HRESULT WINAPI service(const GUID* cls, const GUID* iid, void** out) +{ + if (*cls != submit_async_family || *iid != submit_async_family) return E_NOINTERFACE; + *out = &api; + return S_OK; +} + +template u64 ptr(T* p) { return reinterpret_cast(p); } +u64 call(int slot, u64 a = 0, u64 b = 0, u64 c = 0, u64 d = 0) +{ + u64 args[]{a, b, c, d, 0, 0, 0, 0, 0, 0, 0}, result{}; + if (!save_call(slot, args, &result)) std::abort(); + return result; +} +std::size_t packed_size(const char* name, std::size_t payload) +{ + return sizeof(x2w_save_pack::Blob) + std::strlen(name) + 1 + payload; +} +bool packed_ok(const unsigned char* buffer, std::uint32_t count, const char* name, const unsigned char* payload, std::size_t payload_size) +{ + if (count != 1) return false; + const auto* blob = reinterpret_cast(buffer); + const auto* base = reinterpret_cast(blob); + if (std::strcmp(blob->info.name, name) != 0 || blob->info.size != payload_size) return false; + if (std::memcmp(blob->data, payload, payload_size) != 0) return false; + return reinterpret_cast(blob->info.name) == base + sizeof(x2w_save_pack::Blob) && + blob->data == reinterpret_cast(blob->info.name) + std::strlen(name) + 1; +} +bool unchanged(const unsigned char* buffer, std::size_t bytes, unsigned char fill, std::uint32_t count, std::uint32_t expected) +{ + for (std::size_t i = 0; i < bytes; ++i) + if (buffer[i] != fill) return false; + return count == expected; +} + +HRESULT (WINAPI* result_size)(void*, void*, std::size_t*) = nullptr; +void* result_service = nullptr; +struct Seen { unsigned callbacks{}; HRESULT size_hr{E_FAIL}; std::size_t bytes{}; u64 status{1}; std::uint32_t count{}; bool match{}; }; +Seen seen; +constexpr unsigned char preference_bytes[]{0x41, 0x42, 0x43}; +void WINAPI on_preference(Block* block) +{ + std::size_t bytes = 0; + seen.size_hr = result_size(result_service, block, &bytes); + seen.bytes = bytes; + alignas(x2w_save_pack::Blob) unsigned char buffer[64]; + std::memset(buffer, 0xA5, sizeof buffer); + std::uint32_t count = 0; + seen.status = call(22, ptr(block), bytes, ptr(buffer), ptr(&count)); + seen.count = count; + seen.match = bytes == packed_size("preference", 3) && packed_ok(buffer, count, "preference", preference_bytes, 3); + for (std::size_t i = bytes; i < sizeof buffer && seen.match; ++i) seen.match = buffer[i] == 0xA5; + ++seen.callbacks; +} + +const char* preference_name = "preference"; +const char* other_name = "other"; +constexpr unsigned char other_bytes[]{0x10, 0x20}; + +int commit() +{ + u64 provider_handle{}, container{}, update{}; + const char* names[]{preference_name, other_name}; + if (call(3, local_user_handle, ptr("fixture"), 0, ptr(&provider_handle)) || + call(16, provider_handle, ptr("profile"), ptr(&container)) || + call(23, container, 0, ptr(&update)) || + call(25, update, ptr(names[0]), ptr(preference_bytes), 3) || + call(25, update, ptr(names[1]), ptr(other_bytes), 2) || + call(27, update)) return 1; + std::puts("committed preference and other"); + return 0; +} + +int read_phase(bool system) +{ + void* runtime = nullptr; + void** methods = nullptr; + struct Runtime { + void* service{}; + void* queue{}; + void** methods{}; + ~Runtime() + { + if (methods && queue) reinterpret_cast(methods[17])(service, queue); + if (methods && service) reinterpret_cast(methods[2])(service); + } + } held; + if (system) { + const auto dll = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!dll) return 77; + real_query = reinterpret_cast(GetProcAddress(dll, "QueryApiImpl")); + if (!real_query) return 77; + if (FAILED(real_query(&submit_async_family, &submit_async_family, &runtime)) || !runtime) return 77; + methods = *static_cast(runtime); + held.service = runtime; + held.methods = methods; + using CreateQueue = HRESULT(WINAPI*)(void*, unsigned, unsigned, void**); + if (FAILED(reinterpret_cast(methods[12])(runtime, 3, 3, &held.queue))) return 77; + result_size = reinterpret_cast(methods[4]); + result_service = runtime; + } else { + operations.methods[2] = reinterpret_cast(&drop); + operations.methods[4] = reinterpret_cast(&get_result_size); + operations.methods[7] = reinterpret_cast(&begin); + operations.methods[10] = reinterpret_cast(&complete); + operations.methods[11] = reinterpret_cast(&get_result); + real_query = service; + result_size = reinterpret_cast(&get_result_size); + result_service = &api; + } + + u64 provider_handle{}, container{}; + if (call(3, local_user_handle, ptr("fixture"), 0, ptr(&provider_handle)) || + call(16, provider_handle, ptr("profile"), ptr(&container))) return 2; + if (call(20, container) != 0x80830008) return 3; + + if (!system) { + refuse = true; + Block rejected{}; + const char* names[]{preference_name}; + if (call(21, container, ptr(names), 1, ptr(&rejected)) != static_cast(E_ACCESSDENIED)) return 4; + if (call(22, ptr(&rejected), 64, 0, 0) != static_cast(E_INVALIDARG)) return 4; + refuse = false; + } + + seen = {}; + Block callback_block{}; + callback_block.queue = held.queue; + callback_block.context = &seen; + callback_block.callback = on_preference; + const char* names[]{preference_name}; + if (call(21, container, ptr(names), 1, ptr(&callback_block)) || seen.callbacks != 1 || FAILED(seen.size_hr) || + seen.bytes != packed_size("preference", 3) || seen.status || seen.count != 1 || !seen.match) { + std::printf("callback callbacks=%u size=%08lx bytes=%zu status=%08llx count=%u match=%d\n", + seen.callbacks, static_cast(seen.size_hr), seen.bytes, seen.status, seen.count, seen.match); + return 5; + } + + unsigned char missing_buffer[64]; + std::memset(missing_buffer, 0x3C, sizeof missing_buffer); + std::uint32_t missing_count = 0x22222222; + Block missing{}; + missing.queue = held.queue; + const char* absent = "absent"; + const char* absent_names[]{absent}; + if (call(21, container, ptr(absent_names), 1, ptr(&missing)) || + call(22, ptr(&missing), sizeof missing_buffer, ptr(missing_buffer), ptr(&missing_count)) != 0x80830008 || + !unchanged(missing_buffer, sizeof missing_buffer, 0x3C, missing_count, 0x22222222)) return 6; + + const std::size_t need = packed_size("preference", 3); + alignas(x2w_save_pack::Blob) unsigned char short_buffer[64]; + std::memset(short_buffer, 0x5C, sizeof short_buffer); + std::uint32_t short_count = 0xA5A5A5A5; + Block retry{}; + retry.queue = held.queue; + if (call(21, container, ptr(names), 1, ptr(&retry))) return 7; + if (call(22, ptr(&retry), need - 1, ptr(short_buffer), ptr(&short_count)) != 0x80830007 || + !unchanged(short_buffer, need - 1, 0x5C, short_count, 0xA5A5A5A5)) return 7; + std::memset(short_buffer, 0xA5, sizeof short_buffer); + short_count = 0; + if (call(22, ptr(&retry), need, ptr(short_buffer), ptr(&short_count)) || + !packed_ok(short_buffer, short_count, "preference", preference_bytes, 3)) return 7; + + if (system) { + Block first{}, second{}; + first.queue = second.queue = held.queue; + const char* other_names[]{other_name}; + if (call(21, container, ptr(names), 1, ptr(&first)) || call(21, container, ptr(other_names), 1, ptr(&second))) return 8; + alignas(x2w_save_pack::Blob) unsigned char second_buffer[64]{}; + alignas(x2w_save_pack::Blob) unsigned char first_buffer[64]{}; + std::uint32_t second_count = 0, first_count = 0; + if (call(22, ptr(&second), packed_size("other", 2), ptr(second_buffer), ptr(&second_count)) || + call(22, ptr(&first), need, ptr(first_buffer), ptr(&first_count)) || + !packed_ok(second_buffer, second_count, "other", other_bytes, 2) || + !packed_ok(first_buffer, first_count, "preference", preference_bytes, 3)) return 8; + } else { + Block first{}, second{}; + paused_block = &first; + u64 first_start = 1; + std::thread worker([&] { first_start = call(21, container, ptr(names), 1, ptr(&first)); }); + { + std::unique_lock lock(pending_lock); + progress.wait(lock, [] { return entered; }); + } + alignas(x2w_save_pack::Blob) unsigned char other_buffer[64]; + std::memset(other_buffer, 0x11, sizeof other_buffer); + std::uint32_t other_count = 0x01010101; + const char* other_names[]{other_name}; + const bool second_ok = call(21, container, ptr(other_names), 1, ptr(&second)) == 0 && + call(22, ptr(&second), packed_size("other", 2), ptr(other_buffer), ptr(&other_count)) == 0 && + packed_ok(other_buffer, other_count, "other", other_bytes, 2); + unsigned char pending_buffer[8]; + std::memset(pending_buffer, 0x22, sizeof pending_buffer); + std::uint32_t pending_count = 0x33333333; + const bool still_pending = call(22, ptr(&first), need, ptr(pending_buffer), ptr(&pending_count)) == static_cast(E_PENDING) && + unchanged(pending_buffer, sizeof pending_buffer, 0x22, pending_count, 0x33333333); + { + const std::lock_guard lock(pending_lock); + paused_block = nullptr; + } + progress.notify_one(); + worker.join(); + alignas(x2w_save_pack::Blob) unsigned char first_buffer[64]{}; + std::uint32_t first_count = 0; + if (!second_ok || !still_pending || first_start || + call(22, ptr(&first), need, ptr(first_buffer), ptr(&first_count)) || + !packed_ok(first_buffer, first_count, "preference", preference_bytes, 3)) return 8; + } + std::puts(system ? "system read callback, size, bytes, missing, short, overlap" + : "controlled read refused Begin; callback, size, bytes, missing, short, overlap"); + return 0; +} + +int run_child(const std::string& self, const std::string& arguments) +{ + std::string command = "\"" + self + "\" " + arguments; +#ifdef _WIN32 + command = "\"" + command + "\""; +#endif + const int code = std::system(command.c_str()); +#ifdef _WIN32 + return code; +#else + return code == -1 ? -1 : (code >> 8) & 0xff; +#endif +} +} +int main(int argc, char** argv) +{ + const bool system = argc >= 2 && std::strcmp(argv[1], "system") == 0; + const bool controlled = argc >= 2 && std::strcmp(argv[1], "controlled") == 0; + if (!system && !controlled) return 2; + if (argc >= 3 && std::strcmp(argv[2], "read") == 0) return read_phase(system); + if (commit()) return 1; + return run_child(argv[0], std::string(argv[1]) + " read"); +} diff --git a/tests/startup_gamesave_read_async_check.py b/tests/startup_gamesave_read_async_check.py new file mode 100644 index 000000000..8a7bde658 --- /dev/null +++ b/tests/startup_gamesave_read_async_check.py @@ -0,0 +1,9 @@ +import os +import subprocess +import sys +import tempfile + +with tempfile.TemporaryDirectory() as root: + env = dict(os.environ, X2W_STORAGE_PATH=".", X2W_FAKE_USER="1") + result = subprocess.run(sys.argv[1:], cwd=root, env=env) + sys.exit(result.returncode) From 98c1b94395f88bbb6308de70b63bd7aef007ed50 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:26:29 +0100 Subject: [PATCH 029/775] cpu: keep standard-only XRSTOR default and gate compacted path on --compacted-xrstor --- CMakeLists.txt | 32 +++++++--- tests/cpu/xsave_state_check.py | 106 ++++++++++++++++++++++++--------- tools/cpu_xsave_aot.py | 67 ++++++++++++++------- 3 files changed, 149 insertions(+), 56 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6c90952ee..f8b3bf100 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2264,26 +2264,42 @@ if(EXISTS "${INTAKE_PYTHON}") "op_xrstor64_xsavec64_sse,op_xrstor64_xsavec64_x87_avx,op_xsavec64_dynmask," "op_xrstor64_xsaveopt,op_xrstor64_xsaveopt64,op_xrstor64_xsaveopt64_sse," "op_xrstor64_xsaveopt64_x87_avx,op_xrstor64_xsaveopt64_avx,op_xsaveopt64_dynmask," - "op_xrstor64_sse_compacted_avx_xsaveopt64_avx," - "op_xsavec_xrstor_all,op_xsavec_xrstor_x87_avx,op_xsavec_xrstor_x87_sse," - "op_xsavec_xrstor_avx_only,op_xsavec_xrstor_sse_only,op_xrstor64_compacted_dynmask") + "op_xrstor64_avx_xsaveopt64_avx") string(CONCAT cpu_xsave_state_original_exports ${cpu_xsave_state_original_exports}) set(cpu_xsave_state_altered_exports "op_xrstor64_xsave64,op_xrstor_xsave64,op_xrstor64_disp,op_pipeline," "op_xrstor64_xsavec64,op_xrstor64_xsavec64_sse," - "op_xrstor64_xsaveopt64,op_xrstor64_xsaveopt64_sse," - "op_xsavec_xrstor_all,op_xsavec_xrstor_avx_only") + "op_xrstor64_xsaveopt64,op_xrstor64_xsaveopt64_sse") string(CONCAT cpu_xsave_state_altered_exports ${cpu_xsave_state_altered_exports}) foreach(variant IN ITEMS original altered) cpu_asm_fixture(cpu_xsave_state_${variant} xsave_state) cpu_translation(cpu_xsave_state_${variant} cpu_xsave_aot "${cpu_xsave_state_${variant}_exports}") endforeach() target_compile_definitions(cpu_xsave_state_altered PRIVATE ALTER_OP) + set(cpu_xsave_state_compacted_exports + "op_xrstor64_sse_compacted_avx_xsaveopt64_avx," + "op_xsavec_xrstor_all,op_xsavec_xrstor_x87_avx,op_xsavec_xrstor_x87_sse," + "op_xsavec_xrstor_avx_only,op_xsavec_xrstor_sse_only,op_xrstor64_compacted_dynmask") + string(CONCAT cpu_xsave_state_compacted_exports ${cpu_xsave_state_compacted_exports}) + set(cpu_xsave_state_compacted_cpp "${CMAKE_CURRENT_BINARY_DIR}/cpu_xsave_state_compacted_lifted.cpp") + add_custom_command(OUTPUT "${cpu_xsave_state_compacted_cpp}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/cpu_xsave_aot.py" + "$" "${cpu_xsave_state_compacted_exports}" + "${cpu_xsave_state_compacted_cpp}" --compacted-xrstor + DEPENDS cpu_xsave_state_original tools/cpu_xsave_aot.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_xsave_state_compacted_lifted SHARED "${cpu_xsave_state_compacted_cpp}") + set(cpu_xsave_state_compacted_altered_cpp "${CMAKE_CURRENT_BINARY_DIR}/cpu_xsave_state_compacted_altered_lifted.cpp") + add_custom_command(OUTPUT "${cpu_xsave_state_compacted_altered_cpp}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/cpu_xsave_aot.py" + "$" "op_xsavec_xrstor_all,op_xsavec_xrstor_avx_only" + "${cpu_xsave_state_compacted_altered_cpp}" --compacted-xrstor + DEPENDS cpu_xsave_state_altered tools/cpu_xsave_aot.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_xsave_state_compacted_altered_lifted SHARED "${cpu_xsave_state_compacted_altered_cpp}") set(cpu_xsave_state_canonical_cpp "${CMAKE_CURRENT_BINARY_DIR}/cpu_xsave_state_canonical_lifted.cpp") add_custom_command(OUTPUT "${cpu_xsave_state_canonical_cpp}" COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/cpu_xsave_aot.py" "$" "op_xsave_only,op_xsave64_only,op_xrstor64_avx_xsaveopt64_avx" - "${cpu_xsave_state_canonical_cpp}" --entry-state canonical + "${cpu_xsave_state_canonical_cpp}" --entry-state canonical --compacted-xrstor DEPENDS cpu_xsave_state_original tools/cpu_xsave_aot.py tools/cpu_leaf_aot.py VERBATIM) add_library(cpu_xsave_state_canonical_lifted SHARED "${cpu_xsave_state_canonical_cpp}") set(cpu_xsave_state_canonical_altered_cpp "${CMAKE_CURRENT_BINARY_DIR}/cpu_xsave_state_canonical_altered_lifted.cpp") @@ -2300,7 +2316,9 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$" "$" - "$") + "$" + "$" + "$") set_tests_properties(cpu_aot_xsave_state PROPERTIES SKIP_RETURN_CODE 77) set(cpu_pcmpstr64_exports "pcmpestri64_ub_eqany_pos_lsb,pcmpestri64_sw_ranges_neg_msb," diff --git a/tests/cpu/xsave_state_check.py b/tests/cpu/xsave_state_check.py index 60d15b78c..b79298a91 100644 --- a/tests/cpu/xsave_state_check.py +++ b/tests/cpu/xsave_state_check.py @@ -1120,20 +1120,27 @@ def check_entry_state_contracts( canonical_fns, canonical_altered_lib, canonical_altered_fns, + compacted_lib, + compacted_fns, + compacted_altered_lib, mxcsr_mask: int, deprecates_cs_ds: bool, ) -> None: """Verify explicit entry-state contract metadata and non-default entry controls.""" - for lib, expected_profile, expected_flag in ( - (lifted_lib, b"defined", 0), - (altered_lib, b"defined", 0), - (canonical_lib, b"canonical", 1), - (canonical_altered_lib, b"canonical", 1), + for lib, expected_profile, expected_flag, expected_compacted in ( + (lifted_lib, b"defined", 0, 0), + (altered_lib, b"defined", 0, 0), + (canonical_lib, b"canonical", 1, 1), + (canonical_altered_lib, b"canonical", 1, 0), + (compacted_lib, b"defined", 0, 1), + (compacted_altered_lib, b"defined", 0, 1), ): lib.lifted_entry_state_profile.restype = ctypes.c_char_p lib.lifted_requires_canonical_entry.restype = ctypes.c_uint32 + lib.lifted_allows_compacted_xrstor.restype = ctypes.c_uint32 assert lib.lifted_entry_state_profile() == expected_profile assert lib.lifted_requires_canonical_entry() == expected_flag + assert lib.lifted_allows_compacted_xrstor() == expected_compacted # 1) Non-default incoming SSE state on entry-only XSAVE/XSAVE64 exports: # SSE in use (XSTATE_BV=2), MXCSR=0x3F80, low XMM0 lane=0x3F800000. @@ -1188,17 +1195,27 @@ def check_entry_state_contracts( assert (struct.unpack_from(" XSAVEOPT64(4): - # compacted XRSTOR(4) leaves MXCSR untouched, so native retains caller's 0x3F80 while - # canonical-lifted supplies 0x1F80; standard-format XRSTOR(4) and SSE-defined XRSTOR(2)->XRSTOR(4) - # controls still load 0x5F80 from the image and never observe caller MXCSR. + # 3) Non-default entry-MXCSR control for AVX-only XRSTOR(4) -> XSAVEOPT64(4): + # - Default defined standard-only path accepts AVX-only XRSTOR(4) -> XSAVEOPT64(4), loads 0x5F80 from + # standard_avx (ignoring caller's 0x3F80), and #GPs on compacted_avx. + # - Opt-in compacted + canonical path handles both: compacted_avx leaves caller's 0x3F80 untouched + # natively while canonical-lifted supplies 0x1F80; standard_avx loads 0x5F80. + # - Opt-in compacted + defined SSE-defined positive (XRSTOR(2) -> XRSTOR(4) -> XSAVEOPT64(4)) + # loads 0x5F80 from sse_in before compacted_avx and matches native. compacted_avx = compacted_image(mxcsr_mask, 4, COMPACTED_BIT | 4, 4, mxcsr=0x5F80 & mxcsr_mask, seed=303) standard_avx = make_xsave_image(mxcsr_mask, xstate_bv=4, mxcsr=0x5F80 & mxcsr_mask, seed=304) + got_l_def_std = invoke_lifted(lifted_fns["op_xrstor64_avx_xsaveopt64_avx"], standard_avx, dummy) + assert struct.unpack_from(" None: lifted_lib, lifted = bind_exports( lifted_path, "lifted_", - DEFINED_EXPORTS + (DYNMASK_EXPORT, XSAVEOPT_DYNMASK_EXPORT, SSE_COMPACTED_CONTROL_EXPORT) + COMPACTED_EXPORTS, + DEFINED_EXPORTS + (DYNMASK_EXPORT, XSAVEOPT_DYNMASK_EXPORT, "op_xrstor64_avx_xsaveopt64_avx"), ) lifted_lib.host_has_xsave.argtypes = [] lifted_lib.host_has_xsave.restype = ctypes.c_uint32 @@ -1758,11 +1778,17 @@ def check_differential( _, native = bind_exports(native_path, "", EXPORTS + COMPACTED_EXPORTS + (SSE_COMPACTED_CONTROL_EXPORT,)) native = native_exports_for_host(native, has_xsavec, has_xsaveopt) _, native_altered = bind_exports(native_altered_path, "", ALTERED_CANONICAL_EXPORTS) - altered_lib, altered = bind_exports(altered_path, "lifted_", ALTERED_DEFINED_EXPORTS + ALTERED_COMPACTED_EXPORTS) + altered_lib, altered = bind_exports(altered_path, "lifted_", ALTERED_DEFINED_EXPORTS) canonical_lib, canonical = bind_exports(canonical_path, "lifted_", CANONICAL_EXPORTS) canonical_altered_lib, canonical_altered = bind_exports( canonical_altered_path, "lifted_", ALTERED_CANONICAL_EXPORTS ) + compacted_lib, compacted_lifted = bind_exports( + compacted_path, "lifted_", COMPACTED_EXPORTS + (SSE_COMPACTED_CONTROL_EXPORT,) + ) + compacted_altered_lib, compacted_altered = bind_exports( + compacted_altered_path, "lifted_", ALTERED_COMPACTED_EXPORTS + ) harness = NativeHarness(host_area_size, mxcsr_mask) try: @@ -1778,6 +1804,9 @@ def check_differential( canonical, canonical_altered_lib, canonical_altered, + compacted_lib, + compacted_lifted, + compacted_altered_lib, mxcsr_mask, deprecates_cs_ds, ) @@ -1854,7 +1883,9 @@ def check_differential( liveness_checks = check_xsavec_mxcsr_liveness(harness, native, lifted, mxcsr_mask, deprecates_cs_ds) layout_checks = check_xsaveopt_layout(harness, native, lifted, mxcsr_mask) opt_controls = check_xsaveopt_controls(mxcsr_mask, deprecates_cs_ds) - compacted = check_compacted_xrstor(harness, native, lifted, altered, mxcsr_mask, deprecates_cs_ds) + compacted = check_compacted_xrstor( + harness, native, compacted_lifted, compacted_altered, mxcsr_mask, deprecates_cs_ds + ) # Native comparison keeps active x87/SSE payloads: a flipped FCW, ST0 or XMM0 byte must fail, while an # initialized component carrying extra host bytes must still pass. @@ -1971,8 +2002,15 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.R8)), Instruction.create_mem(Code.XSAVE64_MEM, MemoryOperand(R.R8)), ret_ins))) - # MXCSR is defined by a restore selecting SSE (RFBM[1]); an x87-only save stores no MXCSR, and - # compacted XRSTOR with RFBM=4 (AVX only) leaves MXCSR unchanged. + # Default standard-only XRSTOR defines MXCSR when RFBM selects SSE or AVX; + # opt-in --compacted-xrstor requires RFBM[1] (SSE) because compacted RFBM=4 leaves MXCSR unchanged. + alt_accept.append(("xrstor_avx_vzeroupper_xsaveopt64_avx", ( + mov_eax_4, + xor_edx, + Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), + Instruction.create(Code.VEX_VZEROUPPER), + Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), + ret_ins))) alt_accept.append(("xrstor_sse_vzeroupper_xsaveopt64_avx", ( mov_eax_2, xor_edx, @@ -1988,11 +2026,12 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins))) alt_expected = { - "xrstor_r9_saved_rdx": "op_xrstor(state, r9, rax, rdx, true);", + "xrstor_r9_saved_rdx": "op_xrstor(state, r9, rax, rdx, true, false);", "xrstor3_vzeroupper_xsave7": "op_vzeroupper(state);", "xrstor_xsavec64": "op_xsavec(state, r8, rax, rdx, true);", - "xsavec_then_xrstor_same_buffer": "op_xrstor(state, r8, rax, rdx, true);", + "xsavec_then_xrstor_same_buffer": "op_xrstor(state, r8, rax, rdx, true, false);", "xrstor_xsaveopt64": "op_xsaveopt(state, r8, rax, rdx, true);", + "xrstor_avx_vzeroupper_xsaveopt64_avx": "op_xsaveopt(state, r8, rax, rdx, true);", "xrstor_sse_vzeroupper_xsaveopt64_avx": "op_xsaveopt(state, r8, rax, rdx, true);", "xrstor_x87_xsaveopt64_x87": "op_xsaveopt(state, r8, rax, rdx, true);", "vmovdqa_ymm_roundtrip": "load256(rcx, true)", @@ -2020,7 +2059,16 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) Instruction.create(Code.VEX_VZEROUPPER), Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins)), ): - src, count = lift_code(label, 0x1000, _encode_seq(*seq), entry_state="canonical") + raw = _encode_seq(*seq) + src_def, count_def = lift_code(label, 0x1000, raw) + assert count_def == len(seq) and "Entry-state profile: defined" in src_def, label + try: + lift_code(label, 0x1000, raw, compacted_xrstor=True) + except ValueError as exc: + assert "stores MXCSR before any restore defined it" in str(exc), exc + else: + raise AssertionError(f"{label}: compacted_xrstor=True unexpectedly accepted under defined profile") + src, count = lift_code(label, 0x1000, raw, entry_state="canonical", compacted_xrstor=True) assert count == len(seq) and "Entry-state profile: canonical" in src, label # Also verify runtime #GP for bounded mask contract (EDX != 0 / EAX & ~7 != 0) @@ -2211,21 +2259,23 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) else: raise AssertionError(f"{label}: PE translate accepted rejected patch") - for path, export_name in ( - (original_path, "op_xsave_only"), - (original_path, "op_xsave64_only"), - (original_path, "op_xrstor64_avx_xsaveopt64_avx"), - (altered_path, "op_xrstor64_mask_sse"), + for path, export_name, compacted_opt in ( + (original_path, "op_xsave_only", False), + (original_path, "op_xsave64_only", False), + (original_path, "op_xrstor64_avx_xsaveopt64_avx", True), + (altered_path, "op_xrstor64_mask_sse", False), ): try: - translate(path, [export_name]) + translate(path, [export_name], compacted_xrstor=compacted_opt) except ValueError as exc: if "requires explicit --entry-state canonical" not in str(exc): raise AssertionError(f"{export_name}: unexpected error {exc!r}") from exc else: raise AssertionError(f"{export_name}: default profile unexpectedly accepted uninitialized entry save") - canon_pe_src, _ = translate(original_path, list(CANONICAL_EXPORTS), entry_state="canonical") + def_avx_src, _ = translate(original_path, ["op_xrstor64_avx_xsaveopt64_avx"]) + assert "Entry-state profile: defined" in def_avx_src + canon_pe_src, _ = translate(original_path, list(CANONICAL_EXPORTS), entry_state="canonical", compacted_xrstor=True) assert "Entry-state profile: canonical" in canon_pe_src canon_alt_src, _ = translate(altered_path, ["op_xrstor64_mask_sse"], entry_state="canonical") assert "Entry-state profile: canonical" in canon_alt_src @@ -2237,6 +2287,8 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) if __name__ == "__main__": - orig, lifted, alt, canonical, canonical_alt, native_alt = (Path(p) for p in sys.argv[1:7]) + orig, lifted, alt, canonical, canonical_alt, native_alt, compacted, compacted_alt = ( + Path(p) for p in sys.argv[1:9] + ) check_alt_encodings_and_rejections(orig, native_alt) - check_differential(orig, lifted, alt, canonical, canonical_alt, native_alt) + check_differential(orig, lifted, alt, canonical, canonical_alt, native_alt, compacted, compacted_alt) diff --git a/tools/cpu_xsave_aot.py b/tools/cpu_xsave_aot.py index 3c14642c8..cbe83ebc5 100644 --- a/tools/cpu_xsave_aot.py +++ b/tools/cpu_xsave_aot.py @@ -7,17 +7,23 @@ state (XCR0[2:0] = 7) in a local portable XState struct (leaving host XMM6..15, YMM6..15, x87/MMX and MXCSR untouched across lifted calls). -Entry-state contract (`--entry-state`): +Entry-state contract (`--entry-state`) and XRSTOR format contract (`--compacted-xrstor`): - defined (default): the three-pointer ABI carries no incoming x87/SSE/AVX state; every xsave/xsave64 must only save components previously initialized by a supported xrstor/xrstor64 (or vzeroupper for AVX). Entry-only xsave* and partially initialized restore/save paths that observe uninitialized components from entry are rejected. MXCSR is tracked apart from the - components: only an xrstor whose RFBM selects SSE or AVX defines it, so - vzeroupper alone does not (the format is data, not known when lifting: a compacted - restore selecting AVX without SSE leaves MXCSR alone, and the lifted state then - still holds its reset value 0x1F80), and a save that stores MXCSR (xsaveopt with SSE - or AVX selected, xsave/xsavec with SSE selected) is rejected without it. + components: by default (standard-only XRSTOR), an xrstor whose RFBM selects + SSE or AVX defines MXCSR, so vzeroupper alone does not, and a save that + stores MXCSR (xsaveopt with SSE or AVX selected, xsave/xsavec with SSE + selected) is rejected without it. + - --compacted-xrstor (opt-in): permits XRSTOR to accept compacted headers + (XCOMP_BV[63] set) in addition to standard headers. Because the header + format is data and cannot be distinguished at lift time, a compacted + restore selecting AVX without SSE leaves MXCSR untouched; therefore, with + --compacted-xrstor, only an xrstor whose RFBM selects SSE defines MXCSR + under the defined profile, and AVX-only xrstor -> xsaveopt(AVX) requires + --entry-state canonical (or a prior SSE restore). - canonical (opt-in): permits xsave/xsave64 before full component definition assuming the native caller establishes canonical architectural XSAVE state on entry (FCW=0x037F, FSW=0, FTW=0, FOP=0, FIP=0, FCS=0, FDP=0, FDS=0, @@ -473,7 +479,7 @@ for (unsigned i = 0; i < 8u; ++i) std::memset(state.st[i], 0, 16); } -static inline void op_xrstor(XState& state, word address, word rax_val, word rdx_val, bool is64) { +static inline void op_xrstor(XState& state, word address, word rax_val, word rdx_val, bool is64, bool allow_compacted = false) { const std::uint32_t mask_lo = static_cast(rax_val); const std::uint32_t mask_hi = static_cast(rdx_val); if ((address & 63ull) != 0ull) raise_gp(); @@ -492,8 +498,8 @@ std::memcpy(&xstate_bv, raw + 512, 8); std::memcpy(&xcomp_bv, raw + 520, 8); std::memcpy(&hdr_reserved, raw + 528, 8); - // XCOMP_BV[63] selects the compacted format. Only x87 (bit 0), SSE (bit 1) and AVX (bit 2) exist here. - const bool compacted = (xcomp_bv >> 63) != 0ull; + // XCOMP_BV[63] selects the compacted format when allow_compacted is enabled. + const bool compacted = allow_compacted && ((xcomp_bv >> 63) != 0ull); const std::uint64_t xcomp_components = xcomp_bv & ~(1ull << 63); if (compacted) { // Compacted header: every header byte after XCOMP_BV is reserved, XSTATE_BV must be a subset of the @@ -773,7 +779,7 @@ def flat_address(ins, ptr_origins, *, expected_bytes=None, write=False): return f"({base_name} + {disp:#x}ull)" if disp else base_name -def lift_code(name, start, raw, *, entry_state="defined"): +def lift_code(name, start, raw, *, entry_state="defined", compacted_xrstor=False): """Decode and lift one bounded straight-line XSAVE/XRSTOR leaf function.""" if entry_state not in ENTRY_STATES: raise ValueError(f"unsupported entry-state profile {entry_state!r}") @@ -923,14 +929,19 @@ def require_xsave_masks(ins): is64 = XRSTOR_CODES[ins.code] require_xsave_masks(ins) addr = flat_address(ins, ptr_origins, write=False) - statements.append(f"op_xrstor(state, {addr}, rax, rdx, {'true' if is64 else 'false'});") + statements.append( + f"op_xrstor(state, {addr}, rax, rdx, {'true' if is64 else 'false'}, " + f"{'true' if compacted_xrstor else 'false'});" + ) rax_val = const_gpr.get("rax") rdx_val = const_gpr.get("rdx") if rdx_val == 0 and rax_val is not None and (rax_val & ~7) == 0: defined_xcomp |= rax_val & 7 - # Only RFBM[1] (SSE) guarantees MXCSR is defined across both standard and compacted XRSTOR; - # compacted format with RFBM=4 (AVX only) leaves MXCSR unchanged. - if rax_val & 2: + # Standard-only XRSTOR defines MXCSR whenever RFBM selects SSE or AVX. + # When compacted inputs are allowed, only RFBM[1] (SSE) guarantees MXCSR is defined, + # because compacted XRSTOR with RFBM=4 (AVX only) leaves MXCSR unchanged. + mxcsr_mask_bits = 2 if compacted_xrstor else 6 + if rax_val & mxcsr_mask_bits: defined_mxcsr = True defined_xmm.update(range(6)) defined_ymm.update(range(6)) @@ -1132,33 +1143,35 @@ def require_xsave_masks(ins): return "\n".join(lines), len(instructions) -def lift(pe, name, *, entry_state="defined"): +def lift(pe, name, *, entry_state="defined", compacted_xrstor=False): entry = export_rva(pe, name) raw = bounded_code(pe, entry) - source, count = lift_code(name, entry, raw, entry_state=entry_state) + source, count = lift_code(name, entry, raw, entry_state=entry_state, compacted_xrstor=compacted_xrstor) return source, entry, count -def translate_pe(pe, names, *, entry_state="defined"): +def translate_pe(pe, names, *, entry_state="defined", compacted_xrstor=False): if entry_state not in ENTRY_STATES: raise ValueError(f"unsupported entry-state profile {entry_state!r}") if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: raise ValueError("expected AMD64 PE32+") - lifted = [lift(pe, name, entry_state=entry_state) for name in names] + lifted = [lift(pe, name, entry_state=entry_state, compacted_xrstor=compacted_xrstor) for name in names] is_canonical = 1 if entry_state == "canonical" else 0 + is_compacted = 1 if compacted_xrstor else 0 profile_block = ( - f'\n// Entry-state profile: {entry_state}\n' + f'\n// Entry-state profile: {entry_state} (compacted_xrstor={is_compacted})\n' f'extern "C" __declspec(dllexport) const char* lifted_entry_state_profile() {{ return "{entry_state}"; }}\n' f'extern "C" __declspec(dllexport) std::uint32_t lifted_requires_canonical_entry() {{ return {is_canonical}u; }}\n' + f'extern "C" __declspec(dllexport) std::uint32_t lifted_allows_compacted_xrstor() {{ return {is_compacted}u; }}\n' ) source = PRELUDE + profile_block + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] return source, meta -def translate(image, names, *, entry_state="defined"): +def translate(image, names, *, entry_state="defined", compacted_xrstor=False): with pefile.PE(str(image), fast_load=True) as pe: - return translate_pe(pe, names, entry_state=entry_state) + return translate_pe(pe, names, entry_state=entry_state, compacted_xrstor=compacted_xrstor) if __name__ == "__main__": @@ -1172,9 +1185,19 @@ def translate(image, names, *, entry_state="defined"): default="defined", help="entry-state profile: defined (default, requires prior component definition before xsave) or canonical (opt-in caller-initialized canonical XSAVE state)", ) + parser.add_argument( + "--compacted-xrstor", + action="store_true", + help="opt-in: allow compacted XRSTOR headers (XCOMP_BV[63] set); under defined entry-state, requires SSE RFBM[1] to define MXCSR", + ) args = parser.parse_args() try: - source, meta = translate(args.image, args.exports.split(","), entry_state=args.entry_state) + source, meta = translate( + args.image, + args.exports.split(","), + entry_state=args.entry_state, + compacted_xrstor=args.compacted_xrstor, + ) args.output.write_text(source, encoding="utf-8") for name, entry, count in meta: print(f"{name} at RVA {entry:#x} ({args.entry_state}): {count} instructions") From f4442ee82b0aa68efb07bde07028e22eabacb5c6 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:27:20 +0100 Subject: [PATCH 030/775] tests: test compacted_xrstor=True explicitly for AVX-only MXCSR refusal --- tests/cpu/xsave_state_check.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/tests/cpu/xsave_state_check.py b/tests/cpu/xsave_state_check.py index b79298a91..558a9a274 100644 --- a/tests/cpu/xsave_state_check.py +++ b/tests/cpu/xsave_state_check.py @@ -2116,15 +2116,6 @@ def check_alt_encodings_and_rejections(original_path: Path, altered_path: Path) _encode_seq(Instruction.create(Code.VEX_VZEROUPPER), mov_eax_4, xor_edx, Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins), "stores MXCSR before any restore defined it"), - ("xrstor_avx_xsaveopt64_avx_mxcsr_undefined", - _encode_seq(mov_eax_4, xor_edx, Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), - Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins), - "stores MXCSR before any restore defined it"), - ("xrstor_avx_vzeroupper_xsaveopt64_avx_mxcsr_undefined", - _encode_seq(mov_eax_4, xor_edx, Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), - Instruction.create(Code.VEX_VZEROUPPER), - Instruction.create_mem(Code.XSAVEOPT64_MEM, MemoryOperand(R.R8)), ret_ins), - "stores MXCSR before any restore defined it"), ("x87_restore_vzeroupper_xsaveopt64_x87_avx_mxcsr_undefined", _encode_seq(mov_eax_1, xor_edx, Instruction.create_mem(Code.XRSTOR64_MEM, MemoryOperand(R.RCX)), Instruction.create(Code.VEX_VZEROUPPER), From 88dd9484450d68fbe44235175e387e6146b724ae Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Tue, 24 Nov 2026 12:27:28 +0100 Subject: [PATCH 031/775] shader: lower v_cvt_f64_f32 for statically known sources in pixel_aot The f32 widening follow-up to #1363 agreed in #1325. The source must be statically known (literal, binary32 inline constant, tracked SGPR or a VGPR with known bits), so both binary64 words are computed at translation time. Normal values, signed zero and infinities convert exactly; subnormals, NaNs and unproven inputs are refused. The e64 spellings LLVM 15 prints (-x, |x|, -|x|, neg(literal)) apply abs, then neg, with a signed-zero control that distinguishes the order. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 5 + docs/experiments.md | 1 + tests/form_coverage_check.py | 4 + tests/pixel_aot_check.py | 345 ++++++++++++++++++++++++++++++++++- tools/pixel_aot.py | 91 +++++++++ 5 files changed, 445 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 820ccc686..029f21af1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5902,6 +5902,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_cvt_f64_int_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_cvt_f64_int_${adapter}.txt") + add_test(NAME pixel_aot_cvt_f64_f32_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-cvt-f64-f32 "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_cvt_f64_f32_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_cvt_f64_f32_${adapter}.txt") add_test(NAME pixel_aot_sad_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-sad "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 74731611c..623e148d6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5187,6 +5187,7 @@ The carry-in add and subtracts `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subre The 64-bit multiply-adds `v_mad_u64_u32` and `v_mad_i64_i32` lower as `D = S0 * S1 + S2` modulo 2^64 with two 32-bit factors and a 64-bit `S2`, written to a VGPR pair `v[d:d+1]`. The product is built from `a * b` and the `mul_hi_u32` or `mul_hi_i32` helper of the scalar multiply-high, the add runs on two `uint` words with the carry of the low word added to the high word, and no 64-bit HLSL type is used. The unsigned form zero-extends the factors and writes the carry-out of the 64-bit add (the high-word step wraps) to the lane mask, tracked like a comparison result so that `v_cndmask_b32` can read it. The semantics come from LLVM 15 `VOP3Instructions.td`, which defines both (VOP3B opcodes 374 and 375, as in `tools/disasm_rdna2.py`) as `VOP3b_I64_I1_I32_I32_I64`: a 64-bit result and a one-bit carry-out per lane; they are not checked against the ISA document here and not measured on a console. The carry-out of the signed form is not established here, so the translator has no mask for it: the signed form is accepted only with the discarding `null` destination, which LLVM 15 assembles, and any other destination is refused, so a later read of a mask the signed form seems to have written is refused as an unwritten register. The mask of the unsigned form is `vcc`, `vcc_lo`, one SGPR or an SGPR pair; `null` there is refused. `S0` and `S1` take a register, an inline constant or a literal; `S2` takes a VGPR pair, an aligned SGPR pair or an inline constant from -16 to 64, sign-extended to 64 bits. Unaligned VGPR pairs are accepted because LLVM 15 assembles them (hardware legality is assumed, not measured). A literal `S2`, ` clamp`, any operand modifier, an output modifier, an `_e64` suffix, a destination or `S2` that is not a two-register VGPR range, a mask of the wrong width or alignment, an unwritten register and DPP controls are refused. Four programs export through the `R32G32B32A32_UINT` readback target and are compared bit for bit: `u64_pair` (VGPR-pair `S2` with its carry in `vcc_lo`, and an inline -1 `S2` with its carry in `s60`), `u64_mixed` (SGPR-pair `S2`, an inline factor 3 and an unaligned destination), `i64_pair` and `i64_mixed` (the same for the signed form, with an inline -1 and -3). The unsigned rows cover a carry out of the high word with both factors above 2^31, a carry from the low into the high word without a carry out, a sum that wraps to exactly zero and carries, a zero `S2` and a zero factor; the signed rows cover negative times positive, negative times negative with a negative `S2`, and positive times positive with a negative `S2`. Every input and every exported word is a normal binary32 or zero, which the test asserts. Twenty-three wrong references, each replacing one channel of one row, must report `pixel_mismatch`: the signed product for the unsigned form and the unsigned product for the signed form, a dropped `S2`, a dropped carry-out, a carry-out on a low-to-high carry only, a dropped low-word carry, a dropped carry when the sum wraps to zero, a wrong carry of the inline -1 on a non-zero and a zero product, a zero-extended inline -1 and -3, an inline 3 read as 1 and an inline -3 read as 3, and a dropped high word of `S2`. They run as their own tests, `pixel_aot_mad64_hardware` and `pixel_aot_mad64_warp` (`tests/pixel_aot_check.py draw-mad64`), with their own coverage record, and the LLVM 15 round trip covers the four programs. They passed on the NVIDIA GeForce RTX 3080 (driver 32.0.16.2124) and on WARP (Microsoft Basic Render Driver 10.0.26100.9818), Windows 11 (build 26200). They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_mad64_' -V`. The exact conversions `v_cvt_f64_i32` and `v_cvt_f64_u32` lower as the binary64 value of a 32-bit signed or unsigned integer, written to a VGPR pair `v[d:d+1]` (low word in `v[d]`, high word in `v[d+1]`). Every 32-bit integer is exactly representable in binary64, so there is no rounding and no dependence on a rounding mode. The translator builds both words from `uint` operations and uses no `double` and no `asdouble`: the sign (bit 31 of the signed form, zero otherwise), the magnitude, an exponent of 1023 plus the index of the highest set bit, and the bits below it shifted to the top of the 52-bit fraction. Zero gives +0.0 (both words 0) and `INT_MIN` gives `0xc1e00000_00000000`. The shader therefore needs no double-precision capability, and the draw tests have no capability skip for it (the WARP fault on double comparisons noted for `v_div_fmas_f32` is not reachable). The semantics come from LLVM 15 `VOP1Instructions.td` (`v_cvt_f64_i32` and `v_cvt_f64_u32` are VOP1 with a 64-bit result and a 32-bit integer source); they are not checked against the ISA document here and not measured on a console. LLVM 15 prints the unmodified VOP1 form with the `_e32` suffix and accepts it without; both spellings are lowered, with a VGPR, SGPR, inline-constant or literal source. An `_e64` suffix (with or without modifiers), ` clamp`, an output modifier, DPP, SDWA, a destination that is not a two-register VGPR range (one register, a reversed or three-register range, an SGPR range, a pair that ends above v255), a source that is not one dword or an untracked register, and any use inside a masked region are refused. LLVM 15 itself does not assemble `-v` or `|v|` on the integer source; the translator refuses those spellings as well. The translator tracks the pair as two ordinary numeric words (`alul` and `aluh`): a later integer or binary32 instruction that reads one word, such as `v_add_f32`, still lowers and sees the raw word, and `v_mad_u64_u32` may take the pair as its `S2`. A supported binary64 comparison can consume the pair directly. Binary64 arithmetic and conversions back to binary32 or an integer remain unsupported. Four programs export through the `R32G32B32A32_UINT` readback target and are compared bit for bit with Python's own `struct.pack('> 16`, `B >> 12` and the arithmetic `B >> 16` in the shader and packs those with A, a literal 0x12345 and an inline -16. A word whose high half saturates is not a normal binary32, so those channels are exported through an xor with 0x40000000. Each program runs on two rows. In the first row A is positive and B negative: the unsigned pack must turn the literal, `B >> 12`, A and the negative arithmetic shift into 0xffff, and the signed pack must turn A and the zero-extended `B >> 16` into 0x7fff and keep the inline -16 as 0xfff0. In the second row A is negative, which the signed pack turns into 0x8000, and `B >> 12` is 0xfff, which both packs keep. Every input and every expected result is a normal binary32 or zero, which the test asserts. Fifteen wrong references, each replacing one channel on the first row, must report `pixel_mismatch`: truncation instead of saturation in either half, swapped halves, the signed bound on the unsigned pack and the reverse, a negative source clamped to zero or kept, a value above 32767 kept, and the inline constant read as unsigned. That is 19 draws from 2 compiles and 2 renderer launches. They run as their own tests, `pixel_aot_pack_int16_hardware` and `pixel_aot_pack_int16_warp` (`tests/pixel_aot_check.py draw-pack-int16`), with their own coverage record, and the LLVM 15 round trip covers both programs; LLVM 15 prints the two instructions without an encoding suffix. They passed on the NVIDIA GeForce RTX 3060 (driver 32.0.15.9636) and on WARP (Microsoft Basic Render Driver 10.0.19041.5794), Windows 10 (10.0.19045.6466). They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 6032d1f48..fe87e0ab5 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -324,6 +324,9 @@ def check_shader_records(): mad64_forms = {("VOP3", "v_mad_u64_u32"), ("VOP3", "v_mad_i64_i32")} # The exact 32-bit integer to binary64 conversions are VOP1, accepted in their plain and _e32 spellings. cvt_f64_int_forms = {("VOP1", "v_cvt_f64_i32"), ("VOP1", "v_cvt_f64_u32")} + # The binary32 to binary64 conversion of a statically known source: VOP1 in its plain and _e32 spellings, and the + # VOP3 (_e64) spelling LLVM 15 prints for a source modifier. + cvt_f64_f32_forms = {("VOP1", "v_cvt_f64_f32"), ("VOP3", "v_cvt_f64_f32_e64")} mul24_forms = { ("VOP2", "v_mul_i32_i24"), ("VOP3", "v_mul_i32_i24_e64"), ("VOP2", "v_mul_u32_u24"), ("VOP3", "v_mul_u32_u24_e64"), @@ -369,6 +372,7 @@ def check_shader_records(): assert sad_forms <= covered, (name, sad_forms - covered) assert mad64_forms <= covered, (name, mad64_forms - covered) assert cvt_f64_int_forms <= covered, (name, cvt_f64_int_forms - covered) + assert cvt_f64_f32_forms <= covered, (name, cvt_f64_f32_forms - covered) assert mul24_forms <= covered, (name, mul24_forms - covered) assert sop2_lshl_add_forms <= covered, (name, sop2_lshl_add_forms - covered) assert sop2_absdiff_forms <= covered, (name, sop2_absdiff_forms - covered) diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 2403950e2..5bc639886 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -9491,6 +9491,114 @@ def cvt_f64_int_exported(signed, x, mask=None): return (CVT_F64_INT_SENTINELS[0], lo ^ mask, hi ^ mask, CVT_F64_INT_SENTINELS[1]) +# v_cvt_f64_f32: exact conversion of a statically known binary32 to binary64 in a VGPR pair (LLVM 15 VOP1Instructions.td, +# the VOP1 opcode for v_cvt_f64_f32; every finite binary32 is exact in binary64; not checked against the ISA document +# here and not measured on a console). The translator computes both words at translation time and emits constants, so +# the source has to be static and cannot come from the constant buffer: each row is its own program, and the constant +# buffer carries only the xor mask (s45) and the sentinels (s46, s47). The programs follow the int mode (v12 and v15 +# are the sentinels next to the unaligned pair v[13:14]; the pair is exported as lo ^ M and hi ^ M so that every +# exported word is a normal binary32 or zero, which the test asserts). The references are struct.pack(' 1023, fraction at the top). + assert cvt_f64_f32_ref(0x3F800000) == (0, 0x3FF00000) and cvt_f64_f32_ref(0xBF800000) == (0, 0xBFF00000) + assert cvt_f64_f32_ref(0) == (0, 0) and cvt_f64_f32_ref(0x80000000) == (0, 0x80000000) + assert cvt_f64_f32_ref(0x7F800000) == (0, 0x7FF00000) and cvt_f64_f32_ref(0xFF800000) == (0, 0xFFF00000) + assert cvt_f64_f32_ref(0x3F800001) == (0x20000000, 0x3FF00000) + assert cvt_f64_f32_ref(0x00800000) == (0, 0x38100000) and cvt_f64_f32_ref(0x80800000) == (0, 0xB8100000) + assert cvt_f64_f32_ref(0x7F7FFFFF) == (0xE0000000, 0x47EFFFFF) + # The modifier order is observable: abs first, then neg. -|-0| is -0 where neg first would give +0, and the other + # way round for +0, so a swapped order is a different pair of words on both signed zeros. + assert cvt_f64_f32_ref(0x80000000, True, True) == (0, 0x80000000) != cvt_f64_f32_ref(0x80000000, True, True, False) + assert cvt_f64_f32_ref(0, True, True) == (0, 0x80000000) != cvt_f64_f32_ref(0, True, True, False) + + def program(*lines): + return uncompressed_export([*MAD64_PREFIX, *lines]) + + for good in ("v_cvt_f64_f32 v[12:13], 1.0", "v_cvt_f64_f32_e32 v[12:13], 0", "v_cvt_f64_f32 v[12:13], -0.5", + "v_cvt_f64_f32 v[12:13], 0.15915494", "v_cvt_f64_f32 v[12:13], 4.0", + "v_cvt_f64_f32 v[12:13], 0x3f800001", "v_cvt_f64_f32 v[254:255], 0x80000000", + "v_cvt_f64_f32 v[0:1], 0x7f800000", "v_cvt_f64_f32_e64 v[12:13], -|0x80000000|", + "v_cvt_f64_f32_e64 v[12:13], neg(0x3f800001)"): + translate_int(program(good)) + translate_int(program("s_mov_b32 s60, 0x3f800001", "v_cvt_f64_f32 v[12:13], s60")) + translate_int(program("v_mov_b32_e32 v19, 0x3f800001", "v_cvt_f64_f32_e64 v[12:13], -|v19|")) + # A copy chain of a known constant is still static; the source is read before the pair is written. + translate_int(program("v_mov_b32_e32 v19, 0x3f800001", "v_mov_b32_e32 v20, v19", "v_cvt_f64_f32 v[19:20], v20")) + # A word of the pair is an ordinary numeric register to a later float reader and to the f64 comparisons. + translate_int(program("v_cvt_f64_f32 v[12:13], 1.0", "v_add_f32_e32 v14, v12, v13")) + translate_f64(program("v_cvt_f64_f32 v[12:13], 1.0", "v_cmp_lt_f64_e64 s52, v[12:13], v[12:13]")) + # Refusals with a named reason: a subnormal (the f32 denorm mode has no declared profile), a NaN (#312) and a + # register that is not statically known. + for literal in ("0x00000001", "0x807fffff", "0x007fffff", "0x80000001"): + expect_value_error(translate_int, program(f"v_cvt_f64_f32 v[12:13], {literal}"), "is a subnormal") + expect_value_error(translate_int, program(f"v_mov_b32_e32 v19, {literal}", "v_cvt_f64_f32 v[12:13], v19"), + "is a subnormal") + expect_value_error(translate_int, program(f"v_cvt_f64_f32_e64 v[12:13], -|{literal}|"), "is a subnormal") + for literal in ("0x7fc00000", "0x7f800001", "0xffc00000", "0xffffffff"): + expect_value_error(translate_int, program(f"v_cvt_f64_f32 v[12:13], {literal}"), "is a NaN") + expect_value_error(translate_int, program(f"s_mov_b32 s60, {literal}", "v_cvt_f64_f32 v[12:13], s60"), "is a NaN") + expect_value_error(translate_int, program(f"v_cvt_f64_f32_e64 v[12:13], |{literal}|"), "is a NaN") + for unproven in ("v_cvt_f64_f32 v[12:13], v12", # the interpolated sample x + "v_cvt_f64_f32 v[12:13], v18", # a copy of a constant-buffer word + "v_cvt_f64_f32 v[12:13], s44", # a loaded SGPR + "v_cvt_f64_f32_e64 v[12:13], -v18", "v_cvt_f64_f32_e64 v[12:13], |v12|", + "v_cvt_f64_f32_e64 v[12:13], -|s44|"): + expect_value_error(translate_int, program(unproven), "Unproven runtime input") + # An unproven register stays unproven after the conversion of another value; a literal after it does not help. + expect_value_error(translate_int, program("v_cvt_f64_f32 v[12:13], 1.0", "v_cvt_f64_f32 v[14:15], v12"), + "Unproven runtime input") + # Integer inline constants other than 0 are subnormal or NaN bit patterns, and other decimals are no inline + # constants: all refused. + for bad_inline in ("1", "64", "-1", "-16", "3.0", "0.25", "1e9", "-0", "0x1"): + must_reject(translate_int, program(f"v_cvt_f64_f32 v[12:13], {bad_inline}")) + # Only the unmodified VOP1 spellings and the printed VOP3 modifier spellings are lowered. + for bad in ("v_cvt_f64_f32_e64 v[12:13], 0x3f800001", "v_cvt_f64_f32_e64 v[12:13], 1.0", + "v_cvt_f64_f32_e64 v[12:13], v18", "v_cvt_f64_f32_e64 v[12:13], -0x3f800001", + "v_cvt_f64_f32_e64 v[12:13], neg(v18)", "v_cvt_f64_f32_e64 v[12:13], abs(v18)", + "v_cvt_f64_f32_e64 v[12:13], |v18", "v_cvt_f64_f32_e64 v[12:13], v18|", + "v_cvt_f64_f32_e64 v[12:13], -|v18", "v_cvt_f64_f32_e64 v[12:13], ||v18||", + "v_cvt_f64_f32_e64 v[12:13], |-v18|", "v_cvt_f64_f32_e64 v[12:13], --v18", + "v_cvt_f64_f32_e64 v[12:13], -1.0", "v_cvt_f64_f32_e64 v[12:13], neg(1.0)", + "v_cvt_f64_f32_e64 v[12:13], neg(neg(0x3f800001))", + "v_cvt_f64_f32 v[12:13], -v18", "v_cvt_f64_f32 v[12:13], |v18|", + "v_cvt_f64_f32_e32 v[12:13], -0x3f800001", "v_cvt_f64_f32 v[12:13], abs(0x3f800001)", + "v_cvt_f64_f32_e64 v[12:13], v18 clamp", "v_cvt_f64_f32_e64 v[12:13], -v18 clamp", + "v_cvt_f64_f32 v[12:13], v18 clamp", "v_cvt_f64_f32_e64 v[12:13], v18 mul:2", + "v_cvt_f64_f32_e64 v[12:13], -v18 mul:2", "v_cvt_f64_f32_e64 v[12:13], v18 div:2", + "v_cvt_f64_f32 v[12:13], 0x3f800001 clamp", "v_cvt_f64_f32_e64 v[12:13], -0x3f800001 clamp", + "v_cvt_f64_f32_dpp v[12:13], v18 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_cvt_f64_f32 v[12:13], v18 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_cvt_f64_f32_sdwa v[12:13], v18 dst_sel:DWORD src0_sel:WORD_1", + "v_cvt_f64_f32 v[12:13], v18 src0_sel:WORD_1", + "v_cvt_f64_f32 v12, 1.0", "v_cvt_f64_f32 v[12:12], 1.0", "v_cvt_f64_f32 v[12:14], 1.0", + "v_cvt_f64_f32 v[13:12], 1.0", "v_cvt_f64_f32 v[255:256], 1.0", "v_cvt_f64_f32 v[256:257], 1.0", + "v_cvt_f64_f32 s[12:13], 1.0", "v_cvt_f64_f32 v[012:13], 1.0", "v_cvt_f64_f32 v[12:13]", + "v_cvt_f64_f32 v[12:13], 1.0, 1.0", "v_cvt_f64_f32 v[12:13], v[18:19]", + "v_cvt_f64_f32 v[12:13], s[44:45]", "v_cvt_f64_f32 v[12:13], vcc_lo", + "v_cvt_f64_f32 v[12:13], v99", "v_cvt_f64_f32 v[12:13], s60", "v_cvt_f64_f32 v[12:13], s106"): + must_reject(translate_int, program(bad)) + # Arithmetic on the pair and the conversions back are refused, and so is the conversion in a masked region. + for consumer in ("v_add_f64 v[14:15], v[12:13], v[12:13]", "v_mul_f64 v[14:15], v[12:13], v[12:13]", + "v_cvt_f32_f64_e32 v14, v[12:13]", "v_cvt_i32_f64_e32 v14, v[12:13]", + "v_cvt_u32_f64_e32 v14, v[12:13]", "v_mov_b32_e32 v14, v[12:13]"): + must_reject(translate_int, program("v_cvt_f64_f32 v[12:13], 1.0", consumer)) + must_reject(translate_int, uncompressed_export([ + *MAD64_PREFIX, "v_cmp_lt_f32_e64 vcc_lo, v12, s44", "s_and_saveexec_b64 s[60:61], vcc", + "v_cvt_f64_f32 v[12:13], 1.0", MASKED_OR_RESTORE])) + + def check_carry_in_lowering(): """Static checks for v_add_co_ci_u32, v_sub_co_ci_u32 and v_subrev_co_ci_u32 as written by carry_in_group().""" # v18 and v19 are written by the movs at 20 and 21, the carry-out forms at 22 (vcc_lo) and 23 (s60) write the @@ -13631,6 +13845,7 @@ def check_controls(directory): check_carry_in_lowering() check_mad64_lowering() check_cvt_f64_int_lowering() + check_cvt_f64_f32_lowering() check_sdwa_integer_lowering() check_pack_int16_lowering() check_sat_pack_u8_lowering() @@ -15221,6 +15436,63 @@ def check_f16_literal_fold(directory, assembler, objcopy, library): "v_add_f16_e32 v5, 0, v3", "v_add_f16_e32 v6, 1.0, v3"] +def check_cvt_f64_f32_binary(directory, assembler, objcopy, library): + """LLVM 15 gfx1013 encodings of v_cvt_f64_f32: the VOP1 word, the VOP3 source-modifier bits (abs in bit 8 of the + first dword's high half, neg in bit 29 of the second dword, so -|x| sets both and the order is abs then neg), the + spellings LLVM prints (the plain form as _e32, the modifier forms as _e64, a literal negation as neg(0xL)), and the + forms the assembler cannot encode (DPP, SDWA).""" + source, obj, binary = directory / "cvt_f64_f32.s", directory / "cvt_f64_f32.o", directory / "cvt_f64_f32.bin" + + def assemble(line): + source.write_text(line + chr(10) + "s_endpgm" + chr(10), encoding="ascii") + subprocess.run([assembler, "-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-filetype=obj", source, "-o", obj], check=True, + capture_output=True) + subprocess.run([objcopy, "-O", "binary", "--only-section=.text", obj, binary], check=True) + code = binary.read_bytes() + return code[:-4], disassemble(code, library)[0] + + for line, encoded, text in ( + ("v_cvt_f64_f32 v[13:14], v1", "01211a7e", "v_cvt_f64_f32_e32 v[13:14], v1"), + ("v_cvt_f64_f32_e32 v[13:14], s44", "2c201a7e", "v_cvt_f64_f32_e32 v[13:14], s44"), + ("v_cvt_f64_f32 v[13:14], 1.0", "f2201a7e", "v_cvt_f64_f32_e32 v[13:14], 1.0"), + ("v_cvt_f64_f32 v[13:14], 0x3f800001", "ff201a7e0100803f", "v_cvt_f64_f32_e32 v[13:14], 0x3f800001"), + ("v_cvt_f64_f32 v[13:14], 0x00000001", "81201a7e", "v_cvt_f64_f32_e32 v[13:14], 1"), # folds to an integer + ("v_cvt_f64_f32 v[13:14], 0xffffffff", "c1201a7e", "v_cvt_f64_f32_e32 v[13:14], -1"), + ("v_cvt_f64_f32 v[13:14], -v1", "0d0090d501010020", "v_cvt_f64_f32_e64 v[13:14], -v1"), + ("v_cvt_f64_f32 v[13:14], |v1|", "0d0190d501010000", "v_cvt_f64_f32_e64 v[13:14], |v1|"), + ("v_cvt_f64_f32 v[13:14], -|v1|", "0d0190d501010020", "v_cvt_f64_f32_e64 v[13:14], -|v1|"), + ("v_cvt_f64_f32 v[13:14], -s44", "0d0090d52c000020", "v_cvt_f64_f32_e64 v[13:14], -s44"), + ("v_cvt_f64_f32_e64 v[13:14], neg(0x3f800001)", "0d0090d5ff0000200100803f", + "v_cvt_f64_f32_e64 v[13:14], neg(0x3f800001)"), + ("v_cvt_f64_f32_e64 v[13:14], |0x3f800001|", "0d0190d5ff0000000100803f", + "v_cvt_f64_f32_e64 v[13:14], |0x3f800001|"), + ("v_cvt_f64_f32_e64 v[13:14], -|0x3f800001|", "0d0190d5ff0000200100803f", + "v_cvt_f64_f32_e64 v[13:14], -|0x3f800001|"), + # The assembler folds -0x... as an integer negation of the literal, with no modifier: the lowering refuses it. + ("v_cvt_f64_f32_e64 v[13:14], -0x3f800001", "0d0090d5ff000000ffff7fc0", + "v_cvt_f64_f32_e64 v[13:14], 0xc07fffff"), + ("v_cvt_f64_f32_e64 v[13:14], v1", "0d0090d501010000", "v_cvt_f64_f32_e64 v[13:14], v1"), + ("v_cvt_f64_f32 v[13:14], v1 clamp", "0d8090d501010000", "v_cvt_f64_f32_e64 v[13:14], v1 clamp"), + ("v_cvt_f64_f32 v[13:14], -v1 clamp", "0d8090d501010020", "v_cvt_f64_f32_e64 v[13:14], -v1 clamp"), + ("v_cvt_f64_f32_e64 v[13:14], v1 mul:2", "0d0090d501010008", "v_cvt_f64_f32_e64 v[13:14], v1 mul:2")): + code, decoded = assemble(line) + assert (code.hex(), decoded) == (encoded, text), (line, code.hex(), decoded) + # DPP and SDWA do not assemble for this opcode, so neither can reach the translator from LLVM 15 output. + for line in ("v_cvt_f64_f32 v[13:14], v1 row_shl:1", "v_cvt_f64_f32_sdwa v[13:14], v1 src0_sel:WORD_1"): + try: + assemble(line) + except subprocess.CalledProcessError: + pass + else: + raise AssertionError(f"LLVM 15 assembled {line}") + # The decoded spellings that are not lowered are refused: an unmodified _e64, the folded literal negation, clamp, omod. + for text in ("v_cvt_f64_f32_e64 v[13:14], v1", "v_cvt_f64_f32_e64 v[13:14], 0xc07fffff", + "v_cvt_f64_f32_e64 v[13:14], v1 clamp", "v_cvt_f64_f32_e64 v[13:14], -v1 clamp", + "v_cvt_f64_f32_e64 v[13:14], v1 mul:2", "v_cvt_f64_f32_e32 v[13:14], 1", + "v_cvt_f64_f32_e32 v[13:14], -1"): + must_reject(translate_int, uncompressed_export([*MAD64_PREFIX, text.replace("[13:14]", "[12:13]")])) + + def check_f16_round_binary(directory, assembler, objcopy, library): """LLVM 15 gfx1013 encodings of the binary16 VOP1 rounding forms, the integer folding of a 16-bit literal, and the clamp, omod and modifier spellings that assemble on e64 and that the lowering must refuse.""" @@ -15551,6 +15823,7 @@ def check_binary(directory, assembler, objcopy, library): fixtures.extend((uncompressed_export(carry_in_group(op)), translate_int) for op in CARRY_IN_OPS) fixtures.extend((uncompressed_export(mad64_group(group)), translate_int) for group in MAD64_BODIES) fixtures.extend((cvt_f64_int_group(group), translate_int) for group in CVT_F64_INT_BODIES) + fixtures.extend((cvt_f64_f32_binary_program(group), translate_int) for group in CVT_F64_F32_GROUPS) fixtures.extend((uncompressed_export(sdwa_integer_group(group)), translate_int) for group in SDWA_INT_BODIES) fixtures.extend((uncompressed_export(pack_group(group)), translate_int) for group in PACK_BODIES) fixtures.append((sat_pack_u8_program(), translate_int)) @@ -15620,6 +15893,7 @@ def check_binary(directory, assembler, objcopy, library): check_container_selector(directory, native, library) check_wave32_mask_binary(directory, assembler, objcopy, library) check_exp_en_decoding(directory, assembler, objcopy, library) + check_cvt_f64_f32_binary(directory, assembler, objcopy, library) check_cli_partial_export(directory, assembler, objcopy, library) @@ -16467,6 +16741,74 @@ def add_case(cases, x, mask, words, status): return 0 +def check_cvt_f64_f32_draws(directory, compiler, renderer, backend): + """Draw v_cvt_f64_f32 through the integer readback target, bit for bit. + + The source is static, so each row of each group of cvt_f64_f32_program() is its own program, compiled once and drawn + in one renderer batch: the right words of Python's own double, then negative controls that must report a mismatch: + the two words swapped, the sign of a zero or an operand lost, an infinity exported as a NaN, the exponent one too + high, one fraction bit flipped, a sentinel replaced by a pair word (so a write next to the pair would show) and, for + the -|x| groups, the words of the swapped modifier order. The shader uses no double, so the draws need no + capability. On a desktop GPU the draws establish that the translated shader computes the stated operation, not + what the console does. The words are exported as lo ^ M and hi ^ M because the readback needs normal binary32 + words or zero; the controls are built from the same masked words. + """ + source = directory / "cvt_f64_f32.hlsl" + shader = directory / "cvt_f64_f32.cso" + drawn = {"swapped words": 0, "sign lost": 0, "infinity as NaN": 0, "exponent": 0, "fraction": 0, "sentinel": 0, + "modifier order": 0} + + def add_case(cases, mask, words, status): + constants = bytearray(256) + struct.pack_into("<4I", constants, 12, 0, mask, *CVT_F64_F32_SENTINELS) + case = directory / f"cvt_f64_f32-{len(cases)}.case" + case.write_bytes(bytes(constants) + struct.pack("<4I", *words) * 64) + cases.append((case, status)) + + for group in CVT_F64_F32_GROUPS: + for x in cvt_f64_f32_rows(group): + source.write_text(translate_int(cvt_f64_f32_program(group, x)), encoding="ascii") + compile_shader(compiler, source, shader) + words = cvt_f64_f32_group_ref(group, x) + mask = cvt_f64_f32_mask(words) + first, low, high, last = right = cvt_f64_f32_exported(words, mask) + cases = [] + add_case(cases, mask, right, "pass") + wrong = [] + if words[0] != words[1]: + wrong.append(("swapped words", (first, high, low, last))) + if words[1] & 0x80000000: + wrong.append(("sign lost", (first, low, high ^ 0x80000000, last))) + if words[1] & 0x7FFFFFFF == 0x7FF00000: + wrong.append(("infinity as NaN", (first, low, high ^ 0x00080000, last))) + if words[1] & 0x7FFFFFFF: + wrong.append(("exponent", (first, low, ((high ^ mask) + 0x00100000 & 0xFFFFFFFF) ^ mask, last))) + wrong.append(("fraction", (first, low ^ 1, high, last))) + wrong.append(("sentinel", (low, low, high, last))) + wrong.append(("sentinel", (first, low, high, high))) + if group.endswith("negabs"): + swapped = cvt_f64_f32_group_ref(group, x, abs_first=False) + assert swapped != words, (group, hex(x)) + wrong.append(("modifier order", cvt_f64_f32_exported(swapped, mask))) + for kind, bad in wrong: + assert bad != right, (group, hex(x), kind) + add_case(cases, mask, bad, "mismatch") + drawn[kind] += 1 + try: + run_pixel_batch(renderer, backend, shader, cases) + except subprocess.CalledProcessError as error: + if error.returncode == 77: + return 77 + raise + # The controls are not vacuous: every kind was drawn, the modifier order on both signed zeros and the rows the + # task names (largest and smallest normal, both infinities, a fraction ending in the lowest bit) are in the plain draw. + assert all(drawn.values()), drawn + assert {0, 0x80000000} <= set(cvt_f64_f32_rows("vnegabs")) and 0x80000000 in cvt_f64_f32_rows("lnegabs") + assert {0, 0x80000000, 0x3F800000, 0xBF800000, 0x7F7FFFFF, 0x00800000, 0x80800000, 0x7F800000, 0xFF800000, + 0x3F800001} <= set(cvt_f64_f32_rows("lit")) + return 0 + + def check_carry_in_draws(directory, compiler, renderer, backend): """Draw v_add_co_ci_u32, v_sub_co_ci_u32 and v_subrev_co_ci_u32 through the integer readback target. @@ -20664,7 +21006,7 @@ def main(): if mode in ("draw-blend-scalar", "draw-predicate-rounding", "draw-integer-nc", "draw-e64-integer", "draw-bfm", "draw-brev", "draw-align", "draw-sdwa-integer", "draw-plain-bitscan", "draw-vop3-ternary-int", "draw-swap", - "draw-mac-legacy", "draw-carry-out", "draw-carry-in", "draw-mad64", "draw-cvt-f64-int", "draw-pack-int16", "draw-pack-b32", + "draw-mac-legacy", "draw-carry-out", "draw-carry-in", "draw-mad64", "draw-cvt-f64-int", "draw-cvt-f64-f32", "draw-pack-int16", "draw-pack-b32", "draw-sad", "draw-int16-vop3", "draw-int16-ternary", "draw-compressed-export", "draw-uncompressed-export", "draw-uncompressed-integer-export", @@ -20685,6 +21027,7 @@ def main(): "draw-carry-in": check_carry_in_draws, "draw-mad64": check_mad64_draws, "draw-cvt-f64-int": check_cvt_f64_int_draws, + "draw-cvt-f64-f32": check_cvt_f64_f32_draws, "draw-sdwa-integer": check_sdwa_integer_draws, "draw-bfm": check_bfm_draw, "draw-brev": check_brev_draw, diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 72a243015..097f2fc13 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -1865,6 +1865,63 @@ def require_proven_i32_f32_range(base, has_abs, has_neg, scalar, vector, known_s return eff_bits +CVT_F64_F32_INLINE = {"0": 0x00000000, "0.5": 0x3f000000, "-0.5": 0xbf000000, "1.0": 0x3f800000, "-1.0": 0xbf800000, + "2.0": 0x40000000, "-2.0": 0xc0000000, "4.0": 0x40800000, "-4.0": 0xc0800000, + "0.15915494": 0x3e22f983} +CVT_F64_F32_E64_SOURCE = re.compile(r"neg\((0x[0-9a-f]{1,8})\)|(-?)(\|?)([vs]\d+|0x[0-9a-f]{1,8})(\|?)") + + +def cvt_f64_f32_words(bits): + """Return the (low, high) binary64 words of the exact conversion of binary32 bits, or raise ValueError. + + Exact for every finite normal value: sign kept, exponent rebased from 127 to 1023, the 23-bit fraction placed at + the top of the 52-bit fraction. Zero keeps its sign (hi 0x80000000 for -0) and infinity maps to exponent 0x7ff + with a zero fraction. A subnormal input is refused because the f32 denorm mode (MODE[5:4]) has no declared + profile in this translator, and a NaN is refused (issue 312). + """ + sign, exponent, fraction = bits >> 31, (bits >> 23) & 0xff, bits & 0x7fffff + if exponent == 0xff and fraction: + raise ValueError(f"v_cvt_f64_f32 source 0x{bits:08x} is a NaN") + if exponent == 0 and fraction: + raise ValueError(f"v_cvt_f64_f32 source 0x{bits:08x} is a subnormal") + if exponent == 0: + return 0, sign << 31 + if exponent == 0xff: + return 0, (sign << 31) | 0x7ff00000 + return (fraction & 7) << 29, (sign << 31) | ((exponent - 127 + 1023) << 20) | (fraction >> 3) + + +def cvt_f64_f32_source_bits(base, scalar, vector, pending, sample_dest, known_ssa_bits): + """Return the statically known binary32 bits of the source of v_cvt_f64_f32, or raise ValueError. + + The domain is the one of require_proven_i32_f32_range: a hex literal, a binary32 inline constant, a SGPR that + holds a tracked integer, or a VGPR whose bits known_ssa_bits records. Any other register is an unproven runtime + input. An integer inline constant other than 0 is a subnormal (1..64) or an all-ones NaN pattern (-16..-1), + never a float, and is refused with the other unlisted spellings. + """ + if base in CVT_F64_F32_INLINE: + return CVT_F64_F32_INLINE[base] + if re.fullmatch(r"0x[0-9a-f]{1,8}", base): + return int(base, 16) + if not (m := re.fullmatch(r"([vs])(\d+)", base)): + raise ValueError(f"Unsupported v_cvt_f64_f32 source {base}") + if int(m.group(2)) > (255 if m.group(1) == "v" else 105): + raise ValueError(f"Register out of range: {base}") + if base in pending: + raise ValueError("Constant read before load completion") + if base in sample_dest: + raise ValueError("Sample used before vmcnt wait") + if m.group(1) == "s": + value = scalar.get(base) + if not isinstance(value, int): + raise ValueError(f"Unproven runtime input {base} at v_cvt_f64_f32") + return value & 0xffffffff + ssa = vector.get(base) + if not isinstance(ssa, str) or ssa not in known_ssa_bits: + raise ValueError(f"Unproven runtime input {base} at v_cvt_f64_f32") + return known_ssa_bits[ssa] & 0xffffffff + + def fp_operand(token, scalar, vector, pending, sample_dest, *, quad_values: dict[str, bool] | None = None, ignore_sign=False): if re.fullmatch(r"-\d+", token): @@ -4374,6 +4431,40 @@ def sample_coord(reg): lines.append(f" precise float alu{i}l = asfloat(c{i}u == 0u ? 0u : c{i}f << 21);") lines.append(f" precise float alu{i}h = asfloat(c{i}u == 0u ? 0u : c{i}s | ((1023u + c{i}n) << 20) | (c{i}f >> 11));") vector[names[0]], vector[names[1]] = f"alu{i}l", f"alu{i}h" + elif m := match(r"v_cvt_f64_f32(_e32|_e64)? v\[(0|[1-9]\d*):(0|[1-9]\d*)\], ([^,\s]+)"): + # Exact binary32 to binary64 conversion into a VGPR pair v[d:d+1], for a statically known source only + # (cvt_f64_f32_source_bits). Both result words are computed here, in Python, and emitted as constants: + # no HLSL double, no runtime input. Finite normal values, +-0 and +-infinity convert exactly; + # subnormals, NaNs and unproven registers are refused. LLVM 15 prints the unmodified VOP1 form as _e32; + # the only VOP3 (_e64) spellings it prints for this opcode are -x, |x|, -|x| and neg(0xLITERAL), and + # those are accepted here (abs is applied first, then neg, as in require_proven_i32_f32_range; the order is not checked against the ISA document). An _e64 form without a + # modifier, clamp, omod, DPP and SDWA are left to the fall-through. + suffix, first, last, src = m.groups() + first, last = int(first), int(last) + names = (f"v{first}", f"v{last}") + if (mask != "entry" or last != first + 1 or last > 255 or any(name in sample_dest for name in names)): + raise ValueError("Invalid 32-bit float to binary64 conversion") + has_abs = has_neg = False + if suffix == "_e64": + parts = CVT_F64_F32_E64_SOURCE.fullmatch(src) + if not parts: + raise ValueError(f"Unsupported v_cvt_f64_f32_e64 source {src}") + if parts.group(1): + src, has_neg = parts.group(1), True + else: + neg, bar_open, src, bar_close = parts.groups()[1:] + if bar_open != bar_close or (neg == "" and bar_open == "") or (neg and not bar_open and src.startswith("0x")): + raise ValueError(f"Unsupported v_cvt_f64_f32_e64 source {src}") + has_abs, has_neg = bool(bar_open), bool(neg) + bits = cvt_f64_f32_source_bits(src, scalar, vector, pending, sample_dest, known_ssa_bits) + if has_abs: + bits &= 0x7fffffff + if has_neg: + bits ^= 0x80000000 + low, high = cvt_f64_f32_words(bits) + lines.append(f" precise float alu{i}l = asfloat({low}u);") + lines.append(f" precise float alu{i}h = asfloat({high}u);") + vector[names[0]], vector[names[1]] = f"alu{i}l", f"alu{i}h" elif m := match(rf"v_(add|sub|subrev)_co_ci_u32_(e32|e64) (v\d+), {LANE_MASK}, ([^,\s]+), ([^,\s]+), {LANE_MASK}"): # The carry-out add and subtracts above with a carry or borrow of each lane read from a lane mask. # LLVM 15 prints both encodings with their suffix. The VOP2 (e32) encoding reads and writes VCC and From f9acc69daaa92ad7e7ef5a5e90aed1a852bca701 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:27:37 +0800 Subject: [PATCH 032/775] docs: record the independent BVH differential run on Intel Xe2 The independent BVH checks section lists the RTX 2060, GTX 1060 and both WARP builds. Add the Intel Arc 140T at 491bf25d: all 408 comparisons matched through its inline ray-query backend, the three fault controls kept their signature at witnesses 0, 1 and 31, and every run reported zero D3D12 debug errors and warnings. Docs only. --- docs/experiments.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index e2bf25c1c..2e76acd24 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7135,6 +7135,8 @@ Each scene sends the same 136 rays through a double-precision brute-force CPU te RTX 2060 and WARP each completed 408 comparisons. In fault controls only the custom shader's input changes. Swapping child 0 and 32 addresses changed four results, replaying the previous scene changed 102 and aliasing invalid address high bits changed one. Each fault must alter its designated witness ray. The GTX 1060 with driver 32.0.15.6094 on Windows 10 build 19045.6456 matched all 408 comparisons through DispatchRays. App-local WARP 1.0.22 with Agility SDK 1.620.2 matched all 408 through each DXR path. All three fault witnesses fired in each run. The five-ray and differential checks reported zero D3D12 debug warnings and errors. In-box WARP 10.0.19041.5794 reports no DXR and skips these checks. +On Windows 11 build 26300.9974, the Intel Arc 140T (32.0.101.8132) matched all 408 comparisons through its inline ray-query backend, 136 per epoch with 96, 43 and 92 hits. The fault controls kept their signature: swapping the child 0 and 32 addresses changed four results at witness 0, replaying the previous scene changed 102 at witness 1, and aliasing the high address bits changed one at witness 31, with zero D3D12 debug errors and warnings. + ```powershell $env:XBOX2WINDOWS_ADAPTER = 'GTX 1060' cmake --build --preset dev --target offscreen_check From 71fbc403efdc4637d0b2237b7dd9bcd3f86bec8c Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:28:08 +0100 Subject: [PATCH 033/775] tests/docs: address Codex P2 findings on #1421 --- docs/startup-runtime.md | 3 ++- tests/startup_acphal_apu_free.cpp | 16 +++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index de00907dd..475de20ec 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -472,7 +472,8 @@ longer exhausts the heap. While nothing has been freed the offsets are the ones - A block is aligned in address (a power of two, 16 at least; 0 means 16). Size and alignment are 32 bits. - Null output is `E_POINTER`; size 0 or an alignment that is not a power of two is `E_INVALIDARG`; no - room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and its outputs as they were. + room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and the optional + APU-address output as they were, and writes null to the virtual-address output when non-null. - A block that is reused is zeroed, as fresh heap memory is. - `ApuFree(NULL)` is `S_OK`. An address that does not start a live block (never allocated, inside a block, already freed) is `E_INVALIDARG` and changes nothing. diff --git a/tests/startup_acphal_apu_free.cpp b/tests/startup_acphal_apu_free.cpp index f716dacd8..60ab7b0bb 100644 --- a/tests/startup_acphal_apu_free.cpp +++ b/tests/startup_acphal_apu_free.cpp @@ -143,7 +143,21 @@ void bad_requests() check(take(&out, 0x100000000ull, 16, &apu) == invalid && !out, "size 2^32 is size 0"); check(take(&out, 64, 24, &apu) == invalid && !out && apu == 0xDEADBEEF, "alignment 24"); check(take(&out, 64, 0xFFFFFFFFull, &apu) == invalid && !out, "alignment 2^32-1"); - check(take(&out, 64, 0x80000000ull, &apu) == no_memory && !out, "alignment 2 GiB cannot be met"); + void* probe = take_ok(16); + const auto probe_addr = reinterpret_cast(probe); + check(free_fn(probe) == ok, "free probe"); + const std::uint64_t big_align = 0x80000000ull; + const std::uintptr_t aligned_addr = (probe_addr + big_align - 1) & ~(big_align - 1); + const bool big_align_fits = aligned_addr >= probe_addr && (aligned_addr - probe_addr) + 64 <= usable; + out = const_cast(sentinel); + const long big_hr = take(&out, 64, big_align, &apu); + if (big_align_fits) { + check(big_hr == ok && out && reinterpret_cast(out) == aligned_addr, + "alignment 2 GiB succeeds when heap straddles boundary"); + check(free_fn(out) == ok, "free 2 GiB aligned block"); + } else { + check(big_hr == no_memory && !out && apu == 0xDEADBEEF, "alignment 2 GiB cannot be met"); + } check_empty("refused requests"); void* p = take_ok(0x40, 0); // 0 means the default of 16 From ff2297cc7f045719bc6fdbb626ebf8715a4caa1c Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 19:19:29 +0800 Subject: [PATCH 034/775] shader: lower a gfx1030 four-sample image_msaa_load --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 5 + README.md | 1 + docs/experiments.md | 41 ++++++++ tests/compute_check.cpp | 95 +++++++++++++++++- tests/compute_mimg_msaa.s | 14 +++ tests/compute_mimg_msaa_check.py | 153 +++++++++++++++++++++++++++++ tests/compute_mimg_msaa_input.hlsl | 11 +++ tests/desktop_gpu.h | 2 + tests/offscreen_check.cpp | 7 ++ tools/compute_store_aot.py | 39 +++++++- 11 files changed, 361 insertions(+), 8 deletions(-) create mode 100644 tests/compute_mimg_msaa.s create mode 100644 tests/compute_mimg_msaa_check.py create mode 100644 tests/compute_mimg_msaa_input.hlsl diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b73d82490..2442b7099 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -40,6 +40,7 @@ jobs: python3 -B tests/pixel_aot_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/pixel_compare_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/compute_store_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 + python3 -B tests/compute_mimg_msaa_check.py --binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/mesh_indexed_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/mesh_entry_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/mesh_descriptor_swap_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 diff --git a/CMakeLists.txt b/CMakeLists.txt index 820ccc686..dd41c400b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5510,6 +5510,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mimg_packed_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mimg_packed_${adapter}.txt") + add_test(NAME compute_store_aot_mimg_msaa_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_mimg_msaa_check.py" --draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_mimg_msaa_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mimg_msaa_${adapter}.txt") add_test(NAME compute_store_aot_mimg_store_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mimg-store "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 75dad6a6e..2972ed14d 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 raw vector reads | Lower [indexed `buffer_load_dwordx2/x3/x4`](docs/experiments.md#indexed-gfx1030-raw-vector-reads) and verify channel order, destination/index aliasing and untouched output. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_vector_'` | | gfx1030 image loads | Lower [typed RGBA32 and packed RGBA8 2D reads](docs/experiments.md#gfx1030-2d-image-loads), including explicit mip levels, with 32-bit or `a16` addresses and nonzero `dmask` values. Compare the UAV readback against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_(load|mip|packed)_'` | | gfx1030 image queries | Lower [2D mip dimensions and level count](docs/experiments.md#gfx1030-2d-image-resource-queries) for `image_get_resinfo`. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_resinfo_'` | +| gfx1030 MSAA image load | Lower [`image_msaa_load` for 4× `R32_UINT` 2D input](docs/experiments.md#gfx1030-4-sample-image-load). Compare the four samples per pixel and the untouched UAV words against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_msaa_'` | | gfx1030 image stores | Lower [typed RGBA32 and packed RGBA8 2D writes](docs/experiments.md#gfx1030-2d-image-stores), including fixed explicit mip levels and sparse `dmask` values. Compare all mip levels against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_store_'` | | gfx1030 formatted D16 UINT reads | Lower [indexed `buffer_load_format_d16_*` with caller-declared RGBA16 UINT](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-reads) and verify packed channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_load_format_d16_'` | | gfx1030 raw D16 reads | Lower [indexed D16 byte and short MUBUF loads](docs/experiments.md#indexed-gfx1030-raw-d16-reads) and verify that the other VGPR half stays unchanged. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_d16_'` | diff --git a/docs/experiments.md b/docs/experiments.md index 74731611c..6622feb19 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3135,6 +3135,47 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_resinfo_(warp|hardware)$' -V ``` +### gfx1030 4-sample image load + +`image_msaa_load` with `dim:SQ_RSRC_IMG_2D_MSAA`, `dmask:0xf` and `unorm` +reads four samples of a single channel. The three contiguous 32-bit address +VGPRs hold x, y and a fragment ID that must be statically zero. The four +consecutive destination VGPRs receive samples 0 through 3. The lowering +uses four `Texture2DMS.Load(int2(x, y), sample)` calls at `t0` and +allows the source and destination registers to alias. The descriptor load +must complete with `lgkmcnt(0)` and the image result requires `vmcnt(0)` +before use. See the MIMG section of the +[AMD RDNA 2 ISA](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture). + +Use `--image-descriptor` and `--image-format R32_UINT` with the raw UAV +binding. This declares a matching GFX10 `32_UINT` (20) 2D MSAA descriptor +with identity R selection, base level 0, and last level 2 (four samples). +The translator checks descriptor provenance. The caller supplies matching +resource fields, in-range coordinates and a one-to-one fragment-to-sample +mapping. Other masks, array dimensions, packed addresses or data, NSA, +nonzero or variable fragment IDs, and cache and status flags are outside +this profile. + +The source-built fixture renders an 8×8 `DXGI_FORMAT_R32_UINT` target at 4× +MSAA. The pixel shader encodes x, y, and `SV_SampleIndex` in each sample. +The translated compute shader writes 256 words, and the CPU reference +compares all 320 UAV words including the 64 untouched words. The first +mismatches for repeating sample zero, reversing the sample order, swapping +x/y and changing a sentinel are words 1, 0, 4 and 300 respectively. The +adapter skips with code 77 if it lacks the required render target and +multisample-load support. The GPU check executes translated desktop DXIL. +LLVM 15 assembles the source fixture and the synthetic-container CLI +reproduces the text path's HLSL. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_mimg_msaa_(warp|hardware)$' -V +``` + +```sh +python3 -B tests/compute_mimg_msaa_check.py --binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 +``` + ### gfx1030 2D image stores `image_store`, `image_store_mip`, `image_store_pck` and `image_store_mip_pck` diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index 4309c0006..3243baae0 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -168,9 +168,9 @@ struct StoreCase { static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE shader, D3D12_SHADER_BYTECODE rootBytes, bool conversion_pair = false, const StoreCase* store = nullptr, const std::vector* texels = nullptr, - DXGI_FORMAT texture_format = DXGI_FORMAT_UNKNOWN) + DXGI_FORMAT texture_format = DXGI_FORMAT_UNKNOWN, ID3D12Resource* rendered_texture = nullptr) { - if (texels && !tables) throw std::runtime_error("An image load needs the descriptor-table signature"); + if ((texels || rendered_texture) && !tables) throw std::runtime_error("An image load needs the descriptor-table signature"); ComPtr signature; check(device->CreateRootSignature(0, rootBytes.pShaderBytecode, rootBytes.BytecodeLength, IID_PPV_ARGS(&signature)), "Create compute root signature"); @@ -197,8 +197,8 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE if (tables) { // An image-load case binds its output at u0 and the source texture at t0; the table // signature's UAV range starts at u0, while the root-descriptor path keeps u12. - heap = bind_tables(device, list.Get(), input.Get(), output.Get(), texture.Get(), - texels ? 0 : uavs - 1); + auto* image = rendered_texture ? rendered_texture : texture.Get(); + heap = bind_tables(device, list.Get(), input.Get(), output.Get(), image, image ? 0 : uavs - 1); } else { list->SetComputeRootShaderResourceView(0, input->GetGPUVirtualAddress()); list->SetComputeRootUnorderedAccessView(1, output->GetGPUVirtualAddress()); @@ -317,6 +317,93 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch run_compute(device, true, shader, {compute_tables, sizeof(compute_tables)}, false, &store, &texels, format); } +static ComPtr render_msaa_texture(ID3D12Device* device, D3D12_SHADER_BYTECODE vs, + D3D12_SHADER_BYTECODE ps) +{ + constexpr UINT side = 8; + constexpr DXGI_SAMPLE_DESC samples{4, 0}; + D3D12_FEATURE_DATA_FORMAT_SUPPORT format{DXGI_FORMAT_R32_UINT}; + D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS quality{format.Format, samples.Count}; + constexpr UINT required = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_RENDER_TARGET | + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET | D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &format, sizeof(format))) || + (format.Support1 & required) != required || + FAILED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &quality, sizeof(quality))) || + !quality.NumQualityLevels) + return {}; + + D3D12_RESOURCE_DESC image{}; + image.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + image.Width = image.Height = side; + image.DepthOrArraySize = image.MipLevels = 1; + image.Format = format.Format; + image.SampleDesc = samples; + image.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + auto texture = resource(device, image, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET); + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; + heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + heap_desc.NumDescriptors = 1; + ComPtr heap; + check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "Create MSAA RTV heap"); + const auto rtv = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(texture.Get(), nullptr, rtv); + + D3D12_ROOT_SIGNATURE_DESC layout{}; + ComPtr blob; + check(D3D12SerializeRootSignature(&layout, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr), "Serialize MSAA draw root"); + ComPtr root; + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)), + "Create MSAA draw root"); + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root.Get(); + desc.VS = vs; + desc.PS = ps; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.RasterizerState.MultisampleEnable = TRUE; + desc.SampleMask = UINT_MAX; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = format.Format; + desc.SampleDesc = samples; + ComPtr pipeline; + check(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)), "Create MSAA input draw pipeline"); + ComputeCommands commands(device, pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + auto& list = commands.list; + list->SetGraphicsRootSignature(root.Get()); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const D3D12_VIEWPORT viewport{0, 0, side, side, 0, 1}; + const D3D12_RECT scissor{0, 0, side, side}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + transition(list.Get(), texture.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + commands.submit_and_wait(device); + return texture; +} + +bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, const char* reference, + const char* vs_path, const char* ps_path) +{ + StoreCase store{}; + std::ifstream source(reference, std::ios::binary); + source.read(reinterpret_cast(&store.groups), sizeof(store.groups)); + source.read(reinterpret_cast(store.expected.data()), sizeof(store.expected)); + if (!source || source.peek() != std::char_traits::eof() || store.groups != 1) + throw std::runtime_error("Invalid compute MSAA load reference"); + const auto code = read_texture_shader(path); + const auto vs = read_texture_shader(vs_path), ps = read_texture_shader(ps_path); + auto texture = render_msaa_texture(device, {vs.data(), vs.size()}, {ps.data(), ps.size()}); + if (!texture) return false; + run_compute(device, true, {code.data(), code.size()}, {compute_tables, sizeof(compute_tables)}, + false, &store, nullptr, DXGI_FORMAT_UNKNOWN, texture.Get()); + return true; +} + bool check_compute_texture_store_file(ID3D12Device* device, const char* path, const char* reference) { UINT groups = 0, mip = 0; diff --git a/tests/compute_mimg_msaa.s b/tests/compute_mimg_msaa.s new file mode 100644 index 000000000..abcaa2cf0 --- /dev/null +++ b/tests/compute_mimg_msaa.s @@ -0,0 +1,14 @@ +s_mov_b32 s12, s7 +s_mov_b32 s13, 0 +s_load_dwordx4 s[20:23], s[12:13], 0x30 +s_load_dwordx8 s[24:31], s[12:13], 0x40 +v_lshl_add_u32 v8, s10, 3, v0 +v_lshl_add_u32 v9, s11, 3, v1 +v_mov_b32_e32 v10, 0 +v_mov_b32_e32 v12, v9 +v_lshlrev_b32_e32 v13, 4, v8 +s_waitcnt lgkmcnt(0) +image_msaa_load v[8:11], v[8:10], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm +s_waitcnt vmcnt(0) +buffer_store_dwordx4 v[8:11], v[12:13], s[20:23], 0 idxen offen +s_endpgm diff --git a/tests/compute_mimg_msaa_check.py b/tests/compute_mimg_msaa_check.py new file mode 100644 index 000000000..a5108a727 --- /dev/null +++ b/tests/compute_mimg_msaa_check.py @@ -0,0 +1,153 @@ +"""Check the gfx1030 scalar-format, four-sample image_msaa_load profile.""" +import argparse +import os +from pathlib import Path +import struct +import subprocess +import tempfile + +from compute_store_check import MIMG_BINDING, SENTINEL, aot, gfx1030_binary, rejects, variant + +HERE = Path(__file__).resolve().parent +NAME = "image_msaa_load" +BINDING = MIMG_BINDING | {"image_format": "R32_UINT"} +GROUP = (8, 8, 1) +LINES = (HERE / "compute_mimg_msaa.s").read_text(encoding="ascii").splitlines() +IMAGE = next(line for line in LINES if line.startswith(NAME)) +ADDRESS = "int2(asint(tid.x), asint(tid.y))" + + +def reference(*, samples=(0, 1, 2, 3), swapped_xy=False): + words = [SENTINEL] * 320 + for y in range(8): + for x in range(8): + col, row = (y, x) if swapped_xy else (x, y) + for index, sample in enumerate(samples): + words[32 * y + 4 * x + index] = 0x91000000 + sample * 0x10000 + row * 256 + col + return words + + +def first_mismatch(expected, actual): + return next((i, a, b) for i, (a, b) in enumerate(zip(expected, actual, strict=True)) if a != b) + + +def controls(): + source = aot.lower(LINES, GROUP, **BINDING) + assert "Texture2DMS imageData : register(t0);" in source + for sample in range(4): + assert f"uint image_msaa_0_{sample} = imageData.Load({ADDRESS}, {sample});" in source + store = "uint4(image_msaa_0_0, image_msaa_0_1, image_msaa_0_2, image_msaa_0_3)" + assert store in source + for old, new, message in ( + ("dmask:0xf", "dmask:0x3", "Unsupported compute instruction"), + ("dim:SQ_RSRC_IMG_2D_MSAA", "dim:SQ_RSRC_IMG_2D_MSAA_ARRAY", "Unsupported compute instruction"), + (IMAGE, IMAGE.removesuffix(" unorm"), "Unsupported compute instruction"), + (IMAGE, IMAGE + " a16", "Unsupported compute instruction"), + (IMAGE, IMAGE + " d16", "Unsupported compute instruction"), + (IMAGE, IMAGE + " tfe", "Unsupported compute instruction"), + (IMAGE, IMAGE + " glc", "Unsupported compute instruction"), + ("v[8:10]", "[v8, v9, v10]", "Unsupported compute instruction"), + ("v[8:10]", "v[8:9]", "Invalid image_msaa_load VGPR tuple"), + (IMAGE, IMAGE.replace("v[8:11]", "v[253:256]"), "Invalid image_msaa_load VGPR tuple"), + ("v_mov_b32_e32 v10, 0", "v_mov_b32_e32 v10, 1", "requires a known zero fragment ID"), + ("v_mov_b32_e32 v10, 0", "v_mov_b32_e32 v10, v8", "requires a known zero fragment ID"), + ("s_waitcnt lgkmcnt(0)", "", "Unresolved image descriptor"), + (IMAGE, IMAGE.replace("s[24:31]", "s[32:39]"), "Unverified image descriptor"), + ("s_waitcnt vmcnt(0)", "", "before s_waitcnt vmcnt(0)"), + ): + rejects(message, aot.lower, variant(LINES, (old, new)), GROUP, **BINDING) + rejects("requires gfx1030", aot.lower, LINES, GROUP, **(BINDING | {"cpu": "gfx1013"})) + rejects("R32_UINT MSAA binding", aot.lower, LINES, GROUP, **MIMG_BINDING) + ordinary = "image_load v8, v[8:9], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D" + rejects("Unsupported image load target", aot.lower, variant(LINES, (IMAGE, ordinary)), GROUP, **BINDING) + + expected = reference() + samples = (0, 0, 2, 3) + repeated = (f"imageData.Load({ADDRESS}, 1)", f"imageData.Load({ADDRESS}, 0)") + mutations = ( + ("repeated sample zero", *repeated, reference(samples=samples), (1, 0x91010000, 0x91000000)), + ("reversed samples", store, "uint4(image_msaa_0_3, image_msaa_0_2, image_msaa_0_1, image_msaa_0_0)", + reference(samples=(3, 2, 1, 0)), (0, 0x91000000, 0x91030000)), + ("swapped coordinates", ADDRESS, "int2(asint(tid.y), asint(tid.x))", reference(swapped_xy=True), + (4, 0x91000001, 0x91000100)), + ) + for label, old, new, actual, mismatch in mutations: + assert old in source and new != old, label + i, a, b = first_mismatch(expected, actual) + assert (i, a, b) == mismatch, label + print(f"CPU control {label}: word={i} expected={a:08x} actual={b:08x}", flush=True) + assert all(word != SENTINEL for word in expected[:256]) and expected[256:] == [SENTINEL] * 64 + return source, expected, mutations + + +def compile_shader(dxc, path, entry, target, output): + subprocess.run([dxc, "-T", target, "-E", entry, "-Fo", output, path], check=True) + + +def desktop(directory, dxc, source, expected, mutations, renderer=None, adapter=None): + input_hlsl = HERE / "compute_mimg_msaa_input.hlsl" + vs, ps = directory / "input-vs.dxil", directory / "input-ps.dxil" + compile_shader(dxc, input_hlsl, "vs_main", "vs_6_0", vs) + compile_shader(dxc, input_hlsl, "ps_main", "ps_6_0", ps) + hlsl, dxil, case = (directory / f"{NAME}.{ext}" for ext in ("hlsl", "dxil", "case")) + case.write_bytes(struct.pack("<321I", 1, *expected)) + cmd = [renderer, adapter, "--compute-texture-msaa-case", dxil, case, vs, ps] + variants = [("translated", source, None)] + [ + (label, source.replace(old, new), mismatch) for label, old, new, _, mismatch in mutations] + for label, shader, mismatch in variants: + hlsl.write_text(shader, encoding="ascii") + compile_shader(dxc, hlsl, "main", "cs_6_0", dxil) + if renderer is None: + continue + result = subprocess.run(cmd, capture_output=True, text=True) + print(f"{label}:\n{result.stdout}{result.stderr}", end="", flush=True) + if mismatch is None: + if result.returncode: + return result.returncode + assert "compared_words=320 mismatches=0" in result.stdout + else: + i, a, b = mismatch + assert result.returncode == 1 and f"word={i} expected={a:08x} actual={b:08x}" in result.stderr, label + if renderer is not None: + # Verify that the comparator checks the untouched tail as well as the four outputs per pixel. + wrong = expected.copy() + wrong[300] ^= 1 + case.write_bytes(struct.pack("<321I", 1, *wrong)) + hlsl.write_text(source, encoding="ascii") + compile_shader(dxc, hlsl, "main", "cs_6_0", dxil) + result = subprocess.run(cmd, capture_output=True, text=True) + print(f"wrong sentinel:\n{result.stdout}{result.stderr}", end="", flush=True) + assert result.returncode == 1 and "word=300 expected=c5c5c5c4 actual=c5c5c5c5" in result.stderr + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"{NAME}\n", encoding="ascii") + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + modes = parser.add_mutually_exclusive_group() + modes.add_argument("--binary", nargs=3, metavar=("LLVM_MC", "LLVM_OBJCOPY", "LIBLLVM")) + modes.add_argument("--compile", metavar="DXC") + modes.add_argument("--draw", nargs=3, metavar=("DXC", "RENDERER", "ADAPTER")) + args = parser.parse_args() + source, expected, mutations = controls() + if not (args.binary or args.compile or args.draw): + return 0 + out = HERE.parent / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="compute_mimg_msaa_", dir=out) as tmp: + directory = Path(tmp) + if args.binary: + gfx1030_binary(directory, *args.binary, [(NAME, LINES, BINDING)], NAME, group=GROUP) + elif args.compile: + return desktop(directory, args.compile, source, expected, mutations) + else: + dxc, renderer, adapter = args.draw + return desktop(directory, dxc, source, expected, mutations, renderer, adapter) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/compute_mimg_msaa_input.hlsl b/tests/compute_mimg_msaa_input.hlsl new file mode 100644 index 000000000..4345eeff0 --- /dev/null +++ b/tests/compute_mimg_msaa_input.hlsl @@ -0,0 +1,11 @@ +float4 vs_main(uint vertex : SV_VertexID) : SV_Position +{ + float2 uv = float2((vertex << 1u) & 2u, vertex & 2u); + return float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); +} + +// SV_SampleIndex makes the pixel shader run once per covered sample. +uint ps_main(float4 position : SV_Position, uint sample : SV_SampleIndex) : SV_Target +{ + return 0x91000000u | (sample << 16u) | (uint(position.y) << 8u) | uint(position.x); +} diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 82aa4b527..38d887241 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -30,6 +30,8 @@ void check_spirv_compare_sampler(ID3D12Device* device, const char* shader_path, const char* reference_path, const char* descriptors = nullptr); void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference = nullptr); void check_compute_texture_file(ID3D12Device* device, const char* path, const char* reference); +bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, const char* reference, + const char* vs_path, const char* ps_path); bool check_compute_texture_store_file(ID3D12Device* device, const char* path, const char* reference); void check_ffx_device_init(ID3D12Device* device); void check_ffx_recurrent(ID3D12Device* device); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 037d119a7..ff01023dd 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -513,6 +513,12 @@ OperationResult run_compute_texture_case(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +OperationResult run_compute_texture_msaa_case(const OperationContext& ctx) +{ + return skip_if_false(check_compute_texture_msaa_file(ctx.device, ctx.argv[3], ctx.argv[4], ctx.argv[5], ctx.argv[6]), + "R32_UINT 4x MSAA render target and load support unavailable"); +} + OperationResult run_compute_texture_store_case(const OperationContext& ctx) { return skip_if_false(check_compute_texture_store_file(ctx.device, ctx.argv[3], ctx.argv[4]), @@ -1214,6 +1220,7 @@ const OperationSpec kOperations[] = { {"--compute-store-case", 5, 5, nullptr, kNoGate, run_compute_store_case}, {"--compute-store-case-atomic64", 5, 5, nullptr, kGateComputeAtomic64, run_compute_store_case}, {"--compute-texture-case", 5, 5, nullptr, kNoGate, run_compute_texture_case}, + {"--compute-texture-msaa-case", 7, 7, nullptr, kNoGate, run_compute_texture_msaa_case}, {"--compute-texture-store-case", 5, 5, nullptr, kNoGate, run_compute_texture_store_case}, {"--spirv-sampler-views", 4, 4, nullptr, kGateSm60SamplerViews, run_spirv_sampler_views}, {"--dynamic-sampler-index", 3, 3, nullptr, kGateSm60SamplerViews, run_dynamic_sampler_index}, diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index e28130767..a0bb1fff8 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -78,7 +78,7 @@ # loaded from, not the 9-bit GFX10 format, type, swizzle, level or size fields inside them; the two # 16-byte descriptor slots are bound to t0 for reads or u0 for writes. # Value: (HLSL texel type, channel count). -IMAGE_FORMATS = {"R32G32B32A32_UINT": ("uint4", 4), "R8G8B8A8_UINT": ("uint4", 4)} +IMAGE_FORMATS = {"R32G32B32A32_UINT": ("uint4", 4), "R8G8B8A8_UINT": ("uint4", 4), "R32_UINT": ("uint", 1)} # Template operands are the old LDS word and the source VGPR, both HLSL uints. LDS_RMW = { "ds_add_u32": "({0} + {1})", @@ -209,6 +209,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N image_descriptor is the table byte offset of the 8-dword image descriptor. image_format is the caller's statement of the image format inside it. The image binds to t0 for loads or u0 for stores, where image_uav_mip selects the writable subresource and replaces descriptor_offset. + R32_UINT declares the 4-sample Texture2DMS profile for image_msaa_load. """ dims = checked_group(group) if cpu not in ("gfx1013", "gfx1030"): @@ -217,6 +218,9 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if not 0 <= table_reg <= 105: raise ValueError("Invalid table or thread group binding") image_output = image_uav_mip is not None + image_msaa = image_format == "R32_UINT" + if image_msaa and cpu != "gfx1030": + raise ValueError("The R32_UINT MSAA image binding requires gfx1030") if image_output: if (cpu != "gfx1030" or descriptor_offset is not None or stride is not None or image_descriptor is None or image_format not in ("R32G32B32A32_UINT", "R8G8B8A8_UINT") @@ -1189,6 +1193,32 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("D16 buffer read expression is too large") word = ("alu", field) loading[reg] = word + elif m := re.fullmatch(r"image_msaa_load v\[(\d+):(\d+)\], v\[(\d+):(\d+)\], " + r"s\[(\d+):(\d+)\] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm", line): + first, last, addr, addr_last, base, high = map(int, m.groups()) + if not image_msaa or guard_span is not None: + raise ValueError("image_msaa_load requires an unguarded R32_UINT MSAA binding") + if last != first + 3 or addr_last != addr + 2 or max(last, addr_last) > 255: + raise ValueError("Invalid image_msaa_load VGPR tuple") + if high != base + 7 or base % 4 or pending.intersection(range(base, high + 1)): + raise ValueError("Unresolved image descriptor") + if tuple(scalar.get(base + index) for index in range(8)) != tuple( + (("image", index // 4), index % 4) for index in range(8)): + raise ValueError("Unverified image descriptor") + x, y, fragment = (vector.get(reg) for reg in range(addr, addr_last + 1)) + if not is_word(x) or not is_word(y): + raise ValueError("Unverified image_msaa_load coordinates") + if fragment != 0: + raise ValueError("image_msaa_load requires a known zero fragment ID") + # Snapshot both coordinates before publishing any result, including aliased VADDR/VDATA. + address = f"int2(asint({hlsl_word(x)}), asint({hlsl_word(y)}))" + for sample in range(4): + name = f"image_msaa_{image_step_count}_{sample}" + staged_steps.append((None, f" uint {name} = imageData.Load({address}, {sample});")) + reg = first + sample + vector.pop(reg, None) + loading[reg] = ("alu", name) + image_step_count += 1 elif m := re.fullmatch(r"image_(?Pload|store|get_resinfo)(?P_mip)?(?P_pck(?:_sgn)?)? " r"(?Pv\d+|v\[\d+:\d+\]), (?Pv\d+|v\[\d+:\d+\]), " r"s\[(?P\d+):(?P\d+)\] dmask:0x(?P[0-9a-f]+) " @@ -1206,7 +1236,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N count = len(channels) data = [int(n) for n in re.findall(r"\d+", m["data"])] first, last = data[0], data[-1] - if (cpu != "gfx1030" or image_format is None or guard_span is not None or write != image_output + if (cpu != "gfx1030" or image_format is None or image_msaa or guard_span is not None or write != image_output or len(vaddr) != min(address_words, 2) or vaddr[-1] != vaddr[0] + address_words - 1 or vaddr[-1] > 255 or last != first + count - 1 or not 0 < dmask < (1 << IMAGE_FORMATS[image_format][1]) @@ -1462,7 +1492,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if source_descriptor is not None: cbuffer += "ByteAddressBuffer inputData : register(t0);\n" if image_descriptor is not None and not image_output: - cbuffer += f"Texture2D<{IMAGE_FORMATS[image_format][0]}> imageData : register(t0);\n" + texture_type = "Texture2DMS" if image_msaa else f"Texture2D<{IMAGE_FORMATS[image_format][0]}>" + cbuffer += f"{texture_type} imageData : register(t0);\n" local = "" if staged_steps: body = "\n".join([*(step for _, step in staged_steps), body]) @@ -1507,7 +1538,7 @@ def main(): parser.add_argument("--image-uav-mip", type=int, help="Bind the image to u0 at this mip instead of binding a raw output descriptor") parser.add_argument("--image-format", choices=sorted(IMAGE_FORMATS), - help="Caller statement of the format inside the image descriptor") + help="Caller-declared image format (R32_UINT selects the 4-sample image_msaa_load profile)") args = parser.parse_args() if (args.descriptor_offset is None) == (args.image_uav_mip is None): parser.error("Choose either --descriptor-offset or --image-uav-mip") From 35a913a4d523527886ca567a22b1e7a8c14cde0b Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:30:24 +0100 Subject: [PATCH 035/775] startup_stubs: add GameInput keyboard readings and GetPreviousReading history --- CMakeLists.txt | 3 + src/startup_stubs/gameinput.cpp | 249 +++++++++++++++++++---- tests/startup_gameinput_keys.cpp | 329 +++++++++++++++++++++++++++++++ 3 files changed, 546 insertions(+), 35 deletions(-) create mode 100644 tests/startup_gameinput_keys.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 820ccc686..8edddad0a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -325,6 +325,9 @@ foreach(adapter IN ITEMS hardware warp) set_tests_properties(startup_view_heap_${adapter} PROPERTIES SKIP_RETURN_CODE 77) endforeach() add_executable(startup_stub_consumer tests/startup_stub_consumer.cpp) +add_executable(startup_gameinput_keys tests/startup_gameinput_keys.cpp) +target_compile_features(startup_gameinput_keys PRIVATE cxx_std_17) +add_test(NAME startup_gameinput_keys COMMAND startup_gameinput_keys "$") add_executable(startup_placement_alloc tests/startup_placement_alloc.cpp) target_compile_features(startup_placement_alloc PRIVATE cxx_std_17) target_include_directories(startup_placement_alloc PRIVATE src) diff --git a/src/startup_stubs/gameinput.cpp b/src/startup_stubs/gameinput.cpp index a385434cf..e19def8f3 100644 --- a/src/startup_stubs/gameinput.cpp +++ b/src/startup_stubs/gameinput.cpp @@ -23,9 +23,22 @@ namespace { using u64 = std::uint64_t; +constexpr HRESULT device_not_found = static_cast(0x838A0002); constexpr HRESULT reading_not_found = static_cast(0x838A0003); +constexpr HRESULT reading_too_old = static_cast(0x838A0004); +constexpr std::uint32_t kind_keyboard = 0x00000010; constexpr std::uint32_t kind_gamepad = 0x00040000, kind_controller_bits = 0x0000000E; constexpr std::uint32_t status_connected = 0x47; // connected, input enabled, output enabled, synchronized +constexpr std::size_t max_keys = 32; +constexpr std::size_t history_capacity = 64; + +struct KeyState { + std::uint32_t scanCode; + std::uint32_t codePoint; + std::uint8_t virtualKey; + bool isDeadKey; +}; +static_assert(sizeof(KeyState) == 12, "KeyState layout"); struct GamepadState { std::uint32_t buttons; @@ -169,6 +182,38 @@ GamepadState sample() return s; } +std::uint32_t sample_keys(KeyState* out, std::size_t capacity) +{ + std::uint32_t count = 0; + auto push_vk = [&](std::uint32_t vk) { + if (count >= capacity || vk == 0 || vk > 0xFE) return; + const auto vkey = static_cast(vk); + for (std::uint32_t i = 0; i < count; ++i) + if (out[i].virtualKey == vkey) return; + KeyState ks{}; + ks.scanCode = static_cast(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC)); + const UINT ch = MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR); + if ((ch & 0x80000000u) == 0 && (ch & 0xFFFFu) != 0) ks.codePoint = ch & 0xFFFFu; + ks.virtualKey = vkey; + ks.isDeadKey = false; + out[count++] = ks; + }; + + char env[256]{}; + if (GetEnvironmentVariableA("X2W_INPUT_KEYS", env, sizeof(env)) > 0) { + for (char* item = std::strtok(env, ", "); item && count < capacity; item = std::strtok(nullptr, ", ")) { + unsigned vk = 0; + if (std::sscanf(item, "%x", &vk) == 1) push_vk(vk); + } + } + if (process_has_focus()) { + for (std::uint32_t vk = 0x08; vk <= 0xFE && count < capacity; ++vk) { + if ((GetAsyncKeyState(static_cast(vk)) & 0x8000) != 0) push_vk(vk); + } + } + return count; +} + struct Object { void* const* vtable; LONG refs; @@ -202,27 +247,42 @@ void fill_unknown(void** slots, std::index_sequence) } // ---- device ------------------------------------------------------------------------------ +struct DeviceObj : Object { + const unsigned char* info; +}; Table<32> device_table; -Object the_device{device_table.slots, 1}; unsigned char device_info[0x400]; +unsigned char keyboard_device_info[0x400]; +DeviceObj the_device{{device_table.slots, 1}, device_info}; +DeviceObj the_keyboard_device{{device_table.slots, 1}, keyboard_device_info}; -const void* __stdcall device_get_info(Object*) +const void* __stdcall device_get_info(DeviceObj* self) { static LONG calls; note("Device::GetDeviceInfo", calls); - return device_info; + return self->info; } std::uint32_t __stdcall device_get_status(Object*) { return status_connected; } void __stdcall device_set_rumble(Object*, const void*) {} // ---- readings ---------------------------------------------------------------------------- struct Reading : Object { + std::uint32_t kind; GamepadState state; + std::uint32_t key_count; + KeyState keys[max_keys]; + u64 sequence, timestamp; +}; +struct HistoryEntry { u64 sequence, timestamp; + GamepadState pad; + std::uint32_t key_count; + KeyState keys[max_keys]; }; Table<32> reading_table; volatile LONG64 sequence_counter; -GamepadState last_state; +HistoryEntry history_ring[history_capacity]; +std::size_t history_count; SRWLOCK state_lock = SRWLOCK_INIT; u64 __stdcall reading_release(Reading* self) @@ -231,22 +291,39 @@ u64 __stdcall reading_release(Reading* self) if (left == 0) delete self; return static_cast(left); } -std::uint32_t __stdcall reading_kind(Reading*) { return kind_gamepad; } +std::uint32_t __stdcall reading_kind(Reading* self) { return self->kind; } u64 __stdcall reading_sequence(Reading* self, std::uint32_t) { return self->sequence; } u64 __stdcall reading_timestamp(Reading* self) { return self->timestamp; } -void __stdcall reading_device(Reading*, Object** device) +void __stdcall reading_device(Reading* self, Object** device) { if (device) { - InterlockedIncrement(&the_device.refs); - *device = &the_device; + DeviceObj* d = (self->kind == kind_keyboard) ? &the_keyboard_device : &the_device; + InterlockedIncrement(&d->refs); + *device = d; } } +std::uint32_t __stdcall reading_key_count(Reading* self) +{ + static LONG calls; + note("Reading::GetKeyCount", calls); + if ((self->kind & kind_keyboard) == 0) return 0; + return self->key_count; +} +std::uint32_t __stdcall reading_key_state(Reading* self, std::uint32_t state_array_count, KeyState* state_array) +{ + static LONG calls; + note("Reading::GetKeyState", calls, state_array_count); + if ((self->kind & kind_keyboard) == 0 || !state_array || state_array_count == 0) return 0; + const std::uint32_t count = self->key_count < state_array_count ? self->key_count : state_array_count; + std::memcpy(state_array, self->keys, count * sizeof(KeyState)); + return count; +} const ULONGLONG loaded_at = GetTickCount64(); bool __stdcall reading_gamepad(Reading* self, GamepadState* out) { static LONG calls, presses; note("Reading::GetGamepadState", calls); - if (!out) return false; + if (!out || (self->kind & (kind_gamepad | kind_controller_bits)) == 0) return false; *out = self->state; // Each new button combination the title reads is logged once per change (at most 64 lines). static volatile LONG last_logged; @@ -262,26 +339,92 @@ bool __stdcall reading_gamepad(Reading* self, GamepadState* out) return true; } -// The current state as a reading; the sequence number advances when the state changes. -Reading* current_reading() +bool wants_gamepad(std::uint32_t kind) { return (kind & (kind_gamepad | kind_controller_bits)) != 0; } +bool wants_keyboard(std::uint32_t kind) { return (kind & kind_keyboard) != 0; } +bool wants_any(std::uint32_t kind) { return wants_gamepad(kind) || wants_keyboard(kind); } + +std::uint32_t resolve_reading_kind(std::uint32_t requested, Object* device) +{ + if (device == &the_device) return kind_gamepad; + if (device == &the_keyboard_device) return kind_keyboard; + std::uint32_t result = 0; + if (wants_gamepad(requested)) result |= kind_gamepad; + if (wants_keyboard(requested)) result |= kind_keyboard; + return result; +} + +HistoryEntry capture_current() { - const GamepadState now = sample(); + const GamepadState pad = sample(); + KeyState keys[max_keys]{}; + const std::uint32_t key_count = sample_keys(keys, max_keys); + AcquireSRWLockExclusive(&state_lock); - if (std::memcmp(&now, &last_state, sizeof(now)) != 0 || sequence_counter == 0) { - last_state = now; + bool changed = (history_count == 0); + if (!changed) { + const HistoryEntry& latest = history_ring[static_cast(sequence_counter) % history_capacity]; + if (std::memcmp(&pad, &latest.pad, sizeof(pad)) != 0 || key_count != latest.key_count || + (key_count > 0 && std::memcmp(keys, latest.keys, key_count * sizeof(KeyState)) != 0)) { + changed = true; + } + } + if (changed) { ++sequence_counter; + HistoryEntry& slot = history_ring[static_cast(sequence_counter) % history_capacity]; + slot.sequence = static_cast(sequence_counter); + slot.timestamp = now_microseconds(); + slot.pad = pad; + slot.key_count = key_count; + if (key_count > 0) std::memcpy(slot.keys, keys, key_count * sizeof(KeyState)); + if (history_count < history_capacity) ++history_count; } - const u64 sequence = static_cast(sequence_counter); + const HistoryEntry result = history_ring[static_cast(sequence_counter) % history_capacity]; ReleaseSRWLockExclusive(&state_lock); + return result; +} + +// Returns 0 on hit, -1 if sequence does not exist (not found), -2 if evicted (too old). +int find_history(u64 seq, HistoryEntry& out) +{ + AcquireSRWLockShared(&state_lock); + if (history_count == 0 || seq == 0 || seq > static_cast(sequence_counter)) { + ReleaseSRWLockShared(&state_lock); + return -1; + } + const u64 oldest = static_cast(sequence_counter) - history_count + 1; + if (seq < oldest) { + ReleaseSRWLockShared(&state_lock); + return -2; + } + out = history_ring[seq % history_capacity]; + ReleaseSRWLockShared(&state_lock); + return 0; +} + +Reading* make_reading(const HistoryEntry& entry, std::uint32_t kind, Object* device) +{ auto* reading = new Reading{}; reading->vtable = reading_table.slots; reading->refs = 1; - reading->state = now; - reading->sequence = sequence; - reading->timestamp = now_microseconds(); + reading->kind = resolve_reading_kind(kind, device); + reading->state = entry.pad; + reading->key_count = entry.key_count; + if (entry.key_count > 0) std::memcpy(reading->keys, entry.keys, entry.key_count * sizeof(KeyState)); + reading->sequence = entry.sequence; + reading->timestamp = entry.timestamp; return reading; } -bool wants_gamepad(std::uint32_t kind) { return (kind & (kind_gamepad | kind_controller_bits)) != 0; } + +HRESULT validate_kind_and_device(std::uint32_t kind, Object* device) +{ + if (!wants_any(kind)) return reading_not_found; + if (device) { + if (device != &the_device && device != &the_keyboard_device) return device_not_found; + if (device == &the_device && !wants_gamepad(kind)) return reading_not_found; + if (device == &the_keyboard_device && !wants_keyboard(kind)) return reading_not_found; + } + return S_OK; +} // ---- IGameInput --------------------------------------------------------------------------- Table<32> input_table; @@ -294,8 +437,9 @@ HRESULT __stdcall input_current_reading(Object*, std::uint32_t kind, Object* dev note("GameInput::GetCurrentReading", calls, kind, reinterpret_cast(device)); if (!out) return E_POINTER; *out = nullptr; - if (!wants_gamepad(kind) || (device && device != &the_device)) return reading_not_found; - *out = current_reading(); + const HRESULT check_hr = validate_kind_and_device(kind, device); + if (FAILED(check_hr)) return check_hr; + *out = make_reading(capture_current(), kind, device); return S_OK; } HRESULT __stdcall input_next_reading(Object*, Reading* reference, std::uint32_t kind, Object* device, Reading** out) @@ -304,19 +448,33 @@ HRESULT __stdcall input_next_reading(Object*, Reading* reference, std::uint32_t note("GameInput::GetNextReading", calls, reinterpret_cast(reference), kind); if (!out) return E_POINTER; *out = nullptr; - if (!wants_gamepad(kind) || (device && device != &the_device)) return reading_not_found; - Reading* now = current_reading(); - if (reference && now->sequence <= reference->sequence) { - reading_release(now); - return reading_not_found; - } - *out = now; + if (!reference) return E_INVALIDARG; + const HRESULT check_hr = validate_kind_and_device(kind, device); + if (FAILED(check_hr)) return check_hr; + capture_current(); + HistoryEntry entry{}; + const int found = find_history(reference->sequence + 1, entry); + if (found == -2) return reading_too_old; + if (found != 0) return reading_not_found; + *out = make_reading(entry, kind, device); return S_OK; } -HRESULT __stdcall input_previous_reading(Object*, Reading*, std::uint32_t, Object*, Reading** out) +HRESULT __stdcall input_previous_reading(Object*, Reading* reference, std::uint32_t kind, Object* device, Reading** out) { - if (out) *out = nullptr; - return reading_not_found; + static LONG calls; + note("GameInput::GetPreviousReading", calls, reinterpret_cast(reference), kind); + if (!out) return E_POINTER; + *out = nullptr; + if (!reference) return E_INVALIDARG; + const HRESULT check_hr = validate_kind_and_device(kind, device); + if (FAILED(check_hr)) return check_hr; + if (reference->sequence <= 1) return reading_not_found; + HistoryEntry entry{}; + const int found = find_history(reference->sequence - 1, entry); + if (found == -2) return reading_too_old; + if (found != 0) return reading_not_found; + *out = make_reading(entry, kind, device); + return S_OK; } using DeviceCallback = void(__stdcall*)(u64 token, void* context, Object* device, u64 timestamp, std::uint32_t current, std::uint32_t previous); HRESULT __stdcall input_register_device_callback(Object*, Object* device, std::uint32_t kind, std::uint32_t status_filter, std::uint32_t enumeration, @@ -326,9 +484,14 @@ HRESULT __stdcall input_register_device_callback(Object*, Object* device, std::u note("GameInput::RegisterDeviceCallback", calls, kind, status_filter, enumeration); const u64 value = static_cast(InterlockedIncrement(&tokens)); if (token) *token = value; - // Any enumeration request reports the one gamepad at once (connected). - if (callback && enumeration != 0 && wants_gamepad(kind) && (!device || device == &the_device)) - callback(value, context, &the_device, now_microseconds(), status_connected, 0); + // Any enumeration request reports matching virtual devices at once (connected). + if (callback && enumeration != 0) { + const u64 ts = now_microseconds(); + if (wants_gamepad(kind) && (!device || device == &the_device)) + callback(value, context, &the_device, ts, status_connected, 0); + if (wants_keyboard(kind) && (!device || device == &the_keyboard_device)) + callback(value, context, &the_keyboard_device, ts, status_connected, 0); + } return S_OK; } HRESULT __stdcall input_register_callback(Object*, u64 a, u64 b, u64 c, u64 d, u64 e, u64* token) @@ -350,11 +513,17 @@ HRESULT __stdcall input_register_short_callback(Object*, Object*, void*, void*, } void __stdcall input_stop_callback(Object*, u64) {} bool __stdcall input_unregister_callback(Object*, u64, u64) { return true; } -HRESULT __stdcall input_find_device(Object*, const void*, Object** device) +HRESULT __stdcall input_find_device(Object*, const void* id, Object** device) { static LONG calls; note("GameInput::FindDeviceFrom*", calls); if (!device) return E_POINTER; + if (id && (std::memcmp(id, keyboard_device_info + 0x20, 32) == 0 || + std::memcmp(id, keyboard_device_info + 0x40, 32) == 0)) { + InterlockedIncrement(&the_keyboard_device.refs); + *device = &the_keyboard_device; + return S_OK; + } InterlockedIncrement(&the_device.refs); *device = &the_device; return S_OK; @@ -401,6 +570,8 @@ void build() reading_table.slots[4] = reinterpret_cast(&reading_sequence); reading_table.slots[5] = reinterpret_cast(&reading_timestamp); reading_table.slots[6] = reinterpret_cast(&reading_device); + reading_table.slots[14] = reinterpret_cast(&reading_key_count); + reading_table.slots[15] = reinterpret_cast(&reading_key_state); reading_table.slots[22] = reinterpret_cast(&reading_gamepad); // GameInputDeviceInfo: size, vendor/product of a standard pad, a fixed device id, family, capabilities, supported input. std::uint32_t size = sizeof(device_info); @@ -411,6 +582,14 @@ void build() for (int i = 0; i < 32; ++i) device_info[0x40 + i] = static_cast(0xA0 + i); // deviceRootId const std::uint32_t tail[4] = {2 /* family: Xbox One */, 0, kind_gamepad | kind_controller_bits, 0xF /* rumble motors */}; std::memcpy(device_info + 0x60, tail, sizeof(tail)); + // Virtual keyboard device info. + std::memcpy(keyboard_device_info, &size, 4); + const std::uint16_t kbd_ids[2] = {0x045E, 0x07A5}; + std::memcpy(keyboard_device_info + 4, kbd_ids, 4); + for (int i = 0; i < 32; ++i) keyboard_device_info[0x20 + i] = static_cast(0xB0 + i); + for (int i = 0; i < 32; ++i) keyboard_device_info[0x40 + i] = static_cast(0xB0 + i); + const std::uint32_t kbd_tail[4] = {0 /* family: unknown/PC */, 0, kind_keyboard, 0}; + std::memcpy(keyboard_device_info + 0x60, kbd_tail, sizeof(kbd_tail)); } } // namespace diff --git a/tests/startup_gameinput_keys.cpp b/tests/startup_gameinput_keys.cpp new file mode 100644 index 000000000..ac06ac4b9 --- /dev/null +++ b/tests/startup_gameinput_keys.cpp @@ -0,0 +1,329 @@ +// Source-built verification of GameInput.dll keyboard readings, GetPreviousReading/GetNextReading +// history chain, GetKeyCount/GetKeyState, and negative controls. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include + +namespace { + +constexpr std::uint32_t kind_keyboard = 0x00000010; +constexpr std::uint32_t kind_gamepad = 0x00040000; +constexpr std::uint32_t kind_mouse = 0x00000020; +constexpr std::uint32_t status_connected = 0x00000001; +constexpr std::uint32_t blocking_enumeration = 2; +constexpr HRESULT reading_not_found = static_cast(0x838A0003L); +constexpr HRESULT device_not_found = static_cast(0x838A0002L); + +struct KeyState { + std::uint32_t scanCode; + std::uint32_t codePoint; + std::uint8_t virtualKey; + bool isDeadKey; +}; +static_assert(sizeof(KeyState) == 12, "KeyState layout"); + +struct GamepadState { + std::uint32_t buttons; + float leftTrigger, rightTrigger; + float leftThumbstickX, leftThumbstickY, rightThumbstickX, rightThumbstickY; +}; +static_assert(sizeof(GamepadState) == 28, "GamepadState layout"); + +// Minimal vtable-matching C++ views of GameInput v0 COM interfaces. +struct IGameInputDeviceVtbl; +struct IGameInputDevice { + const void* const* vtbl; +}; + +struct IGameInputReading { + const void* const* vtbl; + + std::uint32_t AddRef() + { + using Fn = std::uint64_t(__stdcall*)(IGameInputReading*); + return static_cast(reinterpret_cast(vtbl[1])(this)); + } + std::uint32_t Release() + { + using Fn = std::uint64_t(__stdcall*)(IGameInputReading*); + return static_cast(reinterpret_cast(vtbl[2])(this)); + } + std::uint32_t GetInputKind() + { + using Fn = std::uint32_t(__stdcall*)(IGameInputReading*); + return reinterpret_cast(vtbl[3])(this); + } + std::uint64_t GetSequenceNumber(std::uint32_t kind) + { + using Fn = std::uint64_t(__stdcall*)(IGameInputReading*, std::uint32_t); + return reinterpret_cast(vtbl[4])(this, kind); + } + void GetDevice(IGameInputDevice** device) + { + using Fn = void(__stdcall*)(IGameInputReading*, IGameInputDevice**); + reinterpret_cast(vtbl[6])(this, device); + } + std::uint32_t GetKeyCount() + { + using Fn = std::uint32_t(__stdcall*)(IGameInputReading*); + return reinterpret_cast(vtbl[14])(this); + } + std::uint32_t GetKeyState(std::uint32_t count, KeyState* states) + { + using Fn = std::uint32_t(__stdcall*)(IGameInputReading*, std::uint32_t, KeyState*); + return reinterpret_cast(vtbl[15])(this, count, states); + } + bool GetGamepadState(GamepadState* state) + { + using Fn = bool(__stdcall*)(IGameInputReading*, GamepadState*); + return reinterpret_cast(vtbl[22])(this, state); + } +}; + +using DeviceCallback = void(__stdcall*)(std::uint64_t token, void* context, IGameInputDevice* device, + std::uint64_t timestamp, std::uint32_t currentStatus, + std::uint32_t previousStatus); + +struct IGameInput { + const void* const* vtbl; + + std::uint32_t Release() + { + using Fn = std::uint64_t(__stdcall*)(IGameInput*); + return static_cast(reinterpret_cast(vtbl[2])(this)); + } + HRESULT GetCurrentReading(std::uint32_t kind, IGameInputDevice* device, IGameInputReading** reading) + { + using Fn = HRESULT(__stdcall*)(IGameInput*, std::uint32_t, IGameInputDevice*, IGameInputReading**); + return reinterpret_cast(vtbl[4])(this, kind, device, reading); + } + HRESULT GetNextReading(IGameInputReading* reference, std::uint32_t kind, IGameInputDevice* device, + IGameInputReading** reading) + { + using Fn = HRESULT(__stdcall*)(IGameInput*, IGameInputReading*, std::uint32_t, IGameInputDevice*, + IGameInputReading**); + return reinterpret_cast(vtbl[5])(this, reference, kind, device, reading); + } + HRESULT GetPreviousReading(IGameInputReading* reference, std::uint32_t kind, IGameInputDevice* device, + IGameInputReading** reading) + { + using Fn = HRESULT(__stdcall*)(IGameInput*, IGameInputReading*, std::uint32_t, IGameInputDevice*, + IGameInputReading**); + return reinterpret_cast(vtbl[6])(this, reference, kind, device, reading); + } + HRESULT RegisterDeviceCallback(IGameInputDevice* device, std::uint32_t kind, std::uint32_t statusFilter, + std::uint32_t enumerationKind, void* context, DeviceCallback callback, + std::uint64_t* token) + { + using Fn = HRESULT(__stdcall*)(IGameInput*, IGameInputDevice*, std::uint32_t, std::uint32_t, + std::uint32_t, void*, DeviceCallback, std::uint64_t*); + return reinterpret_cast(vtbl[9])(this, device, kind, statusFilter, enumerationKind, context, callback, + token); + } + bool UnregisterCallback(std::uint64_t token, std::uint64_t timeoutUs) + { + using Fn = bool(__stdcall*)(IGameInput*, std::uint64_t, std::uint64_t); + return reinterpret_cast(vtbl[13])(this, token, timeoutUs); + } +}; + +struct CallbackCapture { + int count = 0; + IGameInputDevice* devices[4] = {}; + std::uint32_t supported_inputs[4] = {}; +}; + +void __stdcall on_device_callback(std::uint64_t, void* context, IGameInputDevice* device, std::uint64_t, + std::uint32_t current_status, std::uint32_t) +{ + auto* cap = static_cast(context); + if (!cap || (current_status & status_connected) == 0 || cap->count >= 4) return; + using GetInfoFn = const unsigned char*(__stdcall*)(IGameInputDevice*); + const unsigned char* info = reinterpret_cast(device->vtbl[3])(device); + std::uint32_t supported = 0; + if (info) std::memcpy(&supported, info + 0x68, sizeof(supported)); + cap->devices[cap->count] = device; + cap->supported_inputs[cap->count] = supported; + ++cap->count; +} + +int check(bool cond, const char* msg) +{ + if (!cond) { + std::fprintf(stderr, "FAIL: %s\n", msg); + return 1; + } + return 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + const char* dll_path = argc > 1 ? argv[1] : "GameInput.dll"; + HMODULE mod = LoadLibraryA(dll_path); + if (!mod) { + std::fprintf(stderr, "FAIL: LoadLibraryA(%s) failed (%lu)\n", dll_path, GetLastError()); + return 1; + } + + using CreateFn = HRESULT(__stdcall*)(void**); + auto create_fn = reinterpret_cast(GetProcAddress(mod, MAKEINTRESOURCEA(1))); + if (!create_fn) { + std::fprintf(stderr, "FAIL: GameInputCreate ordinal 1 not found\n"); + FreeLibrary(mod); + return 1; + } + + int failures = 0; + void* raw_input = nullptr; + failures += check(create_fn(nullptr) == E_POINTER, "GameInputCreate(nullptr) should return E_POINTER"); + failures += check(create_fn(&raw_input) == S_OK && raw_input != nullptr, "GameInputCreate(&input) should succeed"); + auto* input = static_cast(raw_input); + + // 1. RegisterDeviceCallback enumerates keyboard and gamepad devices. + CallbackCapture cap{}; + std::uint64_t token = 0; + HRESULT hr = input->RegisterDeviceCallback(nullptr, kind_keyboard | kind_gamepad, status_connected, + blocking_enumeration, &cap, &on_device_callback, &token); + failures += check(hr == S_OK && token != 0, "RegisterDeviceCallback(keyboard|gamepad) should succeed"); + failures += check(cap.count == 2, "RegisterDeviceCallback should enumerate 2 devices (gamepad + keyboard)"); + IGameInputDevice* kbd_device = nullptr; + IGameInputDevice* pad_device = nullptr; + for (int i = 0; i < cap.count; ++i) { + if (cap.supported_inputs[i] & kind_keyboard) kbd_device = cap.devices[i]; + if (cap.supported_inputs[i] & kind_gamepad) pad_device = cap.devices[i]; + } + failures += check(kbd_device != nullptr && pad_device != nullptr && kbd_device != pad_device, + "Distinct keyboard and gamepad devices should be enumerated"); + failures += check(input->UnregisterCallback(token, 0), "UnregisterCallback should succeed"); + + // 2. Empty keyboard reading (no X2W_INPUT_KEYS). + SetEnvironmentVariableA("X2W_INPUT_KEYS", nullptr); + IGameInputReading* r0 = nullptr; + hr = input->GetCurrentReading(kind_keyboard, kbd_device, &r0); + failures += check(hr == S_OK && r0 != nullptr, "GetCurrentReading(kind_keyboard) should succeed"); + if (r0) { + failures += check((r0->GetInputKind() & kind_keyboard) != 0, "r0 kind should include keyboard"); + failures += check(r0->GetKeyCount() == 0, "r0 key count should be 0 when no keys are pressed"); + KeyState buf[4]{}; + failures += check(r0->GetKeyState(4, buf) == 0, "r0 GetKeyState should return 0 when empty"); + failures += check(r0->GetKeyState(0, buf) == 0, "r0 GetKeyState(0, buf) should return 0"); + failures += check(r0->GetKeyState(4, nullptr) == 0, "r0 GetKeyState(4, nullptr) should return 0"); + GamepadState gp{}; + failures += check(!r0->GetGamepadState(&gp), "keyboard-only reading should reject GetGamepadState"); + } + + // 3. Inject first key set ("41,57" -> 'A', 'W') and verify GetKeyCount / GetKeyState. + SetEnvironmentVariableA("X2W_INPUT_KEYS", "41,57"); + IGameInputReading* r1 = nullptr; + hr = input->GetCurrentReading(kind_keyboard, kbd_device, &r1); + failures += check(hr == S_OK && r1 != nullptr, "r1 GetCurrentReading should succeed"); + if (r1) { + failures += check(r1->GetKeyCount() == 2, "r1 GetKeyCount should be 2"); + KeyState single[1]{}; + failures += check(r1->GetKeyState(1, single) == 1 && single[0].virtualKey == 0x41, + "r1 GetKeyState(1) should truncate to first key (0x41)"); + KeyState keys[4]{}; + const std::uint32_t got = r1->GetKeyState(4, keys); + failures += check(got == 2, "r1 GetKeyState(4) should return 2"); + failures += check(keys[0].virtualKey == 0x41 && keys[1].virtualKey == 0x57, + "r1 keys should be 0x41 and 0x57"); + failures += check(keys[0].scanCode != 0 && !keys[0].isDeadKey, "r1 key 0 scanCode should be populated"); + if (r0) { + failures += check(r1->GetSequenceNumber(kind_keyboard) > r0->GetSequenceNumber(kind_keyboard), + "r1 sequence should advance after key change"); + } + } + + // 4. Inject second key set ("42" -> 'B') and test GetPreviousReading / GetNextReading chain. + SetEnvironmentVariableA("X2W_INPUT_KEYS", "42"); + IGameInputReading* r2 = nullptr; + hr = input->GetCurrentReading(kind_keyboard, kbd_device, &r2); + failures += check(hr == S_OK && r2 != nullptr, "r2 GetCurrentReading should succeed"); + if (r2) { + failures += check(r2->GetKeyCount() == 1, "r2 GetKeyCount should be 1"); + KeyState k2[2]{}; + failures += check(r2->GetKeyState(2, k2) == 1 && k2[0].virtualKey == 0x42, "r2 key should be 0x42"); + + IGameInputReading* prev = nullptr; + hr = input->GetPreviousReading(r2, kind_keyboard, kbd_device, &prev); + failures += check(hr == S_OK && prev != nullptr, "GetPreviousReading(r2) should succeed"); + if (prev) { + KeyState pk[4]{}; + failures += check(prev->GetKeyCount() == 2, "prev key count should be 2"); + failures += check(prev->GetKeyState(4, pk) == 2 && pk[0].virtualKey == 0x41 && pk[1].virtualKey == 0x57, + "prev keys should match r1 (0x41, 0x57)"); + if (r1) { + failures += check(prev->GetSequenceNumber(kind_keyboard) == r1->GetSequenceNumber(kind_keyboard), + "prev sequence should match r1"); + } + + IGameInputReading* next = nullptr; + hr = input->GetNextReading(prev, kind_keyboard, kbd_device, &next); + failures += check(hr == S_OK && next != nullptr, "GetNextReading(prev) should succeed"); + if (next) { + KeyState nk[2]{}; + failures += check(next->GetKeyCount() == 1 && next->GetKeyState(2, nk) == 1 && + nk[0].virtualKey == 0x42, + "next keys should match r2 (0x42)"); + next->Release(); + } + prev->Release(); + } + } + + // 5. Combined kind_keyboard | kind_gamepad reading + gamepad preservation. + IGameInputReading* combo = nullptr; + hr = input->GetCurrentReading(kind_keyboard | kind_gamepad, nullptr, &combo); + failures += check(hr == S_OK && combo != nullptr, "GetCurrentReading(keyboard|gamepad) should succeed"); + if (combo) { + GamepadState gp{}; + failures += check(combo->GetGamepadState(&gp), "combo reading should support GetGamepadState"); + failures += check(combo->GetKeyCount() == 1, "combo reading should report 1 pressed key"); + combo->Release(); + } + + // 6. Negative controls: null out, wrong kind, mismatched device, null reference for GetPreviousReading. + IGameInputReading* bad = nullptr; + failures += check(input->GetCurrentReading(kind_keyboard, nullptr, nullptr) == E_POINTER, + "GetCurrentReading(null out) should return E_POINTER"); + failures += check(input->GetCurrentReading(kind_mouse, nullptr, &bad) == reading_not_found && bad == nullptr, + "GetCurrentReading(mouse) should return reading_not_found"); + failures += check(input->GetCurrentReading(kind_keyboard, pad_device, &bad) == reading_not_found && bad == nullptr, + "GetCurrentReading(keyboard, pad_device) should return reading_not_found"); + failures += check(input->GetCurrentReading(kind_gamepad, kbd_device, &bad) == reading_not_found && bad == nullptr, + "GetCurrentReading(gamepad, kbd_device) should return reading_not_found"); + failures += check(input->GetPreviousReading(nullptr, kind_keyboard, nullptr, &bad) == E_INVALIDARG && bad == nullptr, + "GetPreviousReading(null ref) should return E_INVALIDARG"); + failures += check(input->GetPreviousReading(r2, kind_keyboard, nullptr, nullptr) == E_POINTER, + "GetPreviousReading(null out) should return E_POINTER"); + if (r2) { + // Unknown device pointer should fail with device_not_found or reading_not_found. + IGameInputDevice fake_device{nullptr}; + hr = input->GetCurrentReading(kind_keyboard, &fake_device, &bad); + failures += check((hr == device_not_found || hr == reading_not_found) && bad == nullptr, + "GetCurrentReading(fake_device) should fail"); + // No next reading past latest. + failures += check(input->GetNextReading(r2, kind_keyboard, kbd_device, &bad) == reading_not_found && + bad == nullptr, + "GetNextReading(latest) should return reading_not_found"); + } + + if (r0) r0->Release(); + if (r1) r1->Release(); + if (r2) r2->Release(); + SetEnvironmentVariableA("X2W_INPUT_KEYS", nullptr); + input->Release(); + FreeLibrary(mod); + if (failures == 0) std::printf("PASS: startup_gameinput_keys\n"); + return failures == 0 ? 0 : 1; +} From a6879558982737bf75e9459e4b99b5afe93297b0 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:30:31 +0100 Subject: [PATCH 036/775] startup_stubs: add R32G32B32A32/R16G16/R32/R16/R8 MSAA and D24_UNORM_S8_UINT console plane sizing --- src/startup_stubs/console_plane_size.h | 16 +++++++++++----- tests/startup_plane_size_check.cpp | 24 +++++++++++++++++++++--- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/startup_stubs/console_plane_size.h b/src/startup_stubs/console_plane_size.h index a38537d66..eb05176c5 100644 --- a/src/startup_stubs/console_plane_size.h +++ b/src/startup_stubs/console_plane_size.h @@ -33,8 +33,13 @@ inline std::uint64_t plane_bytes(std::uint64_t width, std::uint64_t height, std: // Texel bytes of the colour formats answered for multisampling; 0 for every other format. inline unsigned colour_texel_bytes(unsigned format) { + if (format >= 1 && format <= 4) return 16; // R32G32B32A32 if (format >= 9 && format <= 14) return 8; // R16G16B16A16 if (format >= 23 && format <= 32) return 4; // R10G10B10A2, R11G11B10, R8G8B8A8 + if (format >= 33 && format <= 38) return 4; // R16G16 + if (format >= 39 && format <= 43) return 4; // R32 + if (format >= 53 && format <= 59) return 2; // R16 + if (format >= 60 && format <= 65) return 1; // R8, A8 if (format >= 87 && format <= 93) return 4; // B8G8R8A8, B8G8R8X8 return 0; } @@ -55,8 +60,8 @@ inline bool console_plane_shape(const D3D12_RESOURCE_DESC& desc) } // Replaces info with the console size for a description of the shape above that is depth with -// stencil (R32G8X24 family, or the console's 16-bit depth with stencil, formats 118-120) or -// multisampled in one of the colour formats above. Returns false and leaves info alone otherwise. +// stencil (R32G8X24 or R24G8 families, or the console's 16-bit depth with stencil, formats 118-120) +// or multisampled in one of the colour formats above. Returns false and leaves info alone otherwise. // // A desktop failure (size all ones) is kept for the desktop formats: nothing here shows that a // shape desktop rejects is valid on the console. Formats 118-120 do not exist on desktop, so for @@ -67,13 +72,14 @@ inline bool console_plane_size(const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_A using namespace plane_detail; if (!console_plane_shape(desc)) return false; const unsigned format = static_cast(desc.Format); - const bool d32s8 = format >= 19 && format <= 22, d16s8 = format >= 118 && format <= 120; + const bool d32s8 = format >= 19 && format <= 22, d24s8 = format >= 44 && format <= 47; + const bool d16s8 = format >= 118 && format <= 120; const bool desktop_failed = info.SizeInBytes == ~0ull; if (desktop_failed && !d16s8) return false; - // At most 16384 x 16384 texels, 32 bytes of samples a texel and 2048 slices: below 2^45, no overflow. + // At most 16384 x 16384 texels, 128 bytes of samples a texel and 2048 slices: below 2^47, no overflow. const std::uint64_t samples = desc.SampleDesc.Count, slices = desc.DepthOrArraySize; std::uint64_t size = 0; - if (d32s8) { + if (d32s8 || d24s8) { size = plane_bytes(desc.Width, desc.Height, 4 * samples, slices) + plane_bytes(desc.Width, desc.Height, samples, slices); } else if (d16s8) { size = plane_bytes(desc.Width, desc.Height, 2 * samples, slices) + plane_bytes(desc.Width, desc.Height, samples, slices); diff --git a/tests/startup_plane_size_check.cpp b/tests/startup_plane_size_check.cpp index 3c9eb810a..de1884fd7 100644 --- a/tests/startup_plane_size_check.cpp +++ b/tests/startup_plane_size_check.cpp @@ -69,19 +69,37 @@ int main(int argc, char** argv) answered("d32s8 1x1 4 samples", texture(19, 1, 1, 4), {0x400000, 0x400000}, 0x20000); answered("rgba8 1920x1080 4 samples", texture(28, 1920, 1080, 4), {0x2000000, 0x400000}, pad(0x1FE0000, 0x1FB0000)); answered("rgba16f 64x64 2 samples, 3 slices", texture(10, 64, 64, 2, 3), {0x400000, 0x400000}, 0x30000); + // Additional MSAA colour families (R32G32B32A32, R16G16, R32, R16, R8) and D24_UNORM_S8_UINT. + answered("rgba32f 100x100 4 samples", texture(2, 100, 100, 4), {0x400000, 0x400000}, pad(0x100000, 0xA0000)); + answered("rgba32f at the largest dimensions", texture(2, 16384, 16384, 8, 2048), {0x500000000000, 0x400000}, 0x400000000000); + answered("rg16f 1920x1080 4 samples", texture(34, 1920, 1080, 4), {0x2000000, 0x400000}, pad(0x1FE0000, 0x1FB0000)); + answered("rg16_typeless 64x64 4 samples", texture(33, 64, 64, 4), {0x400000, 0x400000}, 0x10000); + answered("r32f 1280x720 2 samples", texture(41, 1280, 720, 2), {0x800000, 0x400000}, pad(0x780000, 0x710000)); + answered("r32_typeless 128x128 4 samples", texture(39, 128, 128, 4), {0x400000, 0x400000}, 0x40000); + answered("r16f 300x200 4 samples", texture(54, 300, 200, 4), {0x400000, 0x400000}, pad(0xC0000, 0x80000)); + answered("r8 256x256 4 samples", texture(61, 256, 256, 4), {0x400000, 0x400000}, 0x40000); + answered("r8 300x300 2 samples", texture(61, 300, 300, 2), {0x400000, 0x400000}, pad(0x60000, 0x30000)); + answered("d24s8 1x1 4 samples", texture(45, 1, 1, 4), {0x400000, 0x400000}, 0x20000); + answered("d24s8 2560x1440 4 samples", texture(45, 2560, 1440, 4), {0x4C00000, 0x400000}, pad(0x4880000, 0x4650000)); + answered("r24g8_typeless 1024x1024", texture(44, 1024, 1024), {0x800000, 0x10000}, 0x500000); // Left alone: formats with the same size on both sides, mip chains, other dimensions, sample // counts and formats outside the rule, and a console size that is not smaller. left_alone("rgba8 single sample", texture(28, 2560, 1440), {0xF00000, 0x10000}); + left_alone("rg16f single sample", texture(34, 1024, 1024), {0x400000, 0x10000}); left_alone("d32 without stencil", texture(40, 2560, 1440), {0xF00000, 0x10000}); - left_alone("d24s8", texture(45, 2560, 1440), {0xF00000, 0x10000}); + left_alone("d24s8 single sample already smaller", texture(45, 2560, 1440), {0xF00000, 0x10000}); left_alone("d32s8 with mips", texture(19, 1024, 1024, 1, 1, 3), {0xA80000, 0x10000}); - left_alone("r8 4 samples", texture(61, 256, 256, 4), {0x400000, 0x400000}); + left_alone("bc1 4 samples", texture(71, 256, 256, 4), {0x400000, 0x400000}); + left_alone("rgb32f 4 samples", texture(6, 256, 256, 4), {0x400000, 0x400000}); left_alone("rgba8 3 samples", texture(28, 256, 256, 3), {0x400000, 0x400000}); + left_alone("rgba32f 3 samples", texture(2, 256, 256, 3), {0x400000, 0x400000}); left_alone("d32s8 already smaller", texture(19, 2048, 2048), {0x1400000, 0x10000}); // A desktop failure is kept for desktop formats, valid shape or not. left_alone("d32s8 after a desktop failure", texture(19, 2048, 2048), {~0ull, 0}); + left_alone("d24s8 after a desktop failure", texture(45, 2048, 2048), {~0ull, 0}); left_alone("rgba8 4 samples after a desktop failure", texture(28, 256, 256, 4), {~0ull, 0}); + left_alone("rgba32f 4 samples after a desktop failure", texture(2, 256, 256, 4), {~0ull, 0}); // Shapes outside the rule keep whatever desktop said, including for the console-only formats. D3D12_RESOURCE_DESC shape = texture(19, 2048, 2048); shape.Width = ~0ull; // would wrap while padding to a tile @@ -131,6 +149,6 @@ int main(int argc, char** argv) std::printf("startup_plane_size: %d FAILED\n", failures); return 1; } - std::printf("startup_plane_size: PASS (13 answered, 25 left alone)\n"); + std::printf("startup_plane_size: PASS (24 answered, 29 left alone)\n"); return 0; } From ebb3ab799587957eb48981e104b41351bfd1cbc4 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:30:31 +0800 Subject: [PATCH 037/775] docs: record the BC7 draw fixture on Intel Xe2 The BC7 draw paragraph lists WARP and an RTX 5080 across 8,192 texels and 32,768 channels. Append the Intel Arc 140T run of bc7_draw_hardware at 491bf25d: every case reported max_absolute_error=0, including the 8,192-texel 512-block fixture, the 5,760-texel tiled draw and the mip and tail cases up to 262,144 pixels, with zero D3D12 debug errors and warnings. Docs only. --- docs/experiments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index 74731611c..86975692e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7496,7 +7496,7 @@ ctest --preset dev --no-tests=error -R '^bc7_block_reference$' -V python -B tools/bc7_blocks.py out/bc7_fields.case --fields out/bc7_fields.json ``` -The test compares the first bit of each field group with offsets transcribed from the published mode layouts, checks that every anchor texel lies in its subset, and decodes three blocks whose texels are worked out by hand in the test comments. It also decodes the mode-6 blocks of the draw fixture, which builds its own reference texels, and pins SHA-256 digests of the generated block rows and texels. When the optional `texture2ddecoder` package is installed, the test additionally compares 16,897 decoded blocks with that decoder. This comparison is skipped otherwise. The command above writes the fixture in the `BC7C` case layout. The `bc7_draw_warp` and `bc7_draw_hardware` checks also draw the 512-block fixture. WARP 10.0.26100.9818 and an RTX 5080 on driver 32.0.16.1692 each matched the CPU reference across 8,192 texels and 32,768 channels. Flipping the rotation bit of a mode-4 block while retaining the original reference produced the first mismatch at (16, 0). +The test compares the first bit of each field group with offsets transcribed from the published mode layouts, checks that every anchor texel lies in its subset, and decodes three blocks whose texels are worked out by hand in the test comments. It also decodes the mode-6 blocks of the draw fixture, which builds its own reference texels, and pins SHA-256 digests of the generated block rows and texels. When the optional `texture2ddecoder` package is installed, the test additionally compares 16,897 decoded blocks with that decoder. This comparison is skipped otherwise. The command above writes the fixture in the `BC7C` case layout. The `bc7_draw_warp` and `bc7_draw_hardware` checks also draw the 512-block fixture. WARP 10.0.26100.9818 and an RTX 5080 on driver 32.0.16.1692 each matched the CPU reference across 8,192 texels and 32,768 channels. Flipping the rotation bit of a mode-4 block while retaining the original reference produced the first mismatch at (16, 0). On Windows 11 build 26300.9974, the Intel Arc 140T (32.0.101.8132) matched the CPU reference in every case of `bc7_draw_hardware` with `max_absolute_error=0`: the 8,192-texel 512-block fixture, the 5,760-texel tiled draw, and each mip and tail case up to 262,144 pixels, with zero D3D12 debug errors and warnings throughout. The optional capture contains verified, top-down RGBA8 pixels converted from the GPU readback. The mip test binds both levels in one texture and renders to a half-size target so implicit derivatives select the lower mip. An original mode-6 fixture varies endpoints by block and indices by texel. The negative control shifts only the lower level's compressed blocks and requires a pixel mismatch. [Microsoft BC7 mode reference](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format-mode-reference) From 1f43422006125e11ca8d710a0548b9505abf8550 Mon Sep 17 00:00:00 2001 From: The Void Date: Tue, 24 Nov 2026 12:31:03 +0100 Subject: [PATCH 038/775] shader: lower a forward s_cbranch_scc0/scc1 skip over vector ALU in pixel_aot A forward branch on a tracked scalar compare skips a block for the whole wave. Each VGPR the block writes merges at the target with a select on the condition under which the block runs (SCC for scc0, !SCC for scc1), reusing the masked-region definedness rules. The target must be a later instruction boundary; memory, EXEC, scalar and wave updates, waits and nested branches or regions stay refused. Refs #1413 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 5 ++ docs/experiments.md | 2 + tests/form_coverage_check.py | 4 +- tests/pixel_aot_check.py | 119 ++++++++++++++++++++++++++++++++++- tools/pixel_aot.py | 37 ++++++++++- 5 files changed, 164 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 820ccc686..203590e17 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5638,6 +5638,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_exec_regions_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_exec_regions_${adapter}.txt") + add_test(NAME pixel_aot_scc_skip_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-scc-skip "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_scc_skip_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_scc_skip_${adapter}.txt") add_test(NAME pixel_aot_cmpx_regions_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-cmpx-regions "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 74731611c..000a295fc 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -703,6 +703,8 @@ The source-built fixtures render an 8x8 ramp through three programs: a masked re Either opener may also switch the region once to its else arm with `s_andn2_b64 exec, s[a:b], exec` on the saved pair (issue #1315). EXEC then holds the saved lanes whose condition is false, so the else arm runs on the negated region condition. The else arm starts from the pre-region vector state: it reads a register the then arm wrote at its value from before the region, and a register first defined by the then arm is undefined there until the else arm writes it. At the close each register merges as `condition ? then : else`, with the pre-region value standing in for an arm that did not write it. A register undefined before the region and not written on both arms stays undefined after the close. An optional `s_cbranch_execz` directly after the opener must land exactly on the transition, and one directly after the transition must land exactly on the close. Only the arms of one region may carry skips. `s_andn2_b64` writes SCC from the new EXEC, which is untracked, so SCC is unknown in the else arm until an admitted scalar compare redefines it. A scalar written in a then arm that the wave may skip is undefined in the else arm. The body rules above apply to both arms. A transition naming another pair, a second transition, a transition outside a region, a then-arm skip onto the close of a region with an else, misplaced skips, wave32 `s_andn2_b32 exec_lo` and nesting reject. `check_masked_else_draw`, part of `pixel_aot_exec_regions_{warp,hardware}`, draws one region whose then arm writes v13 and v14 and whose else arm writes v13 and reads v14 into v15. It covers both openers, both closes and the four skip shapes (none, then, else, both) at the mixed, full and empty thresholds. Three mutants must mismatch: the transition removed, the predicate reversed, and an expectation whose else arm reads the then arm's v14. On WARP 10.0.26100.9818 and an AMD Radeon RX 9070 XT (driver 32.0.31044.16), Windows 11 build 26300.9974, all 48 cases matched and all three mutants mismatched. LLVM 15 assembles and disassembles the 16 programs, including the labelled skips. +A forward `s_cbranch_scc0` or `s_cbranch_scc1` on a tracked scalar compare (`s_cmp_*`, `s_bitcmp*`; issue #1413) skips a block of per-lane vector ALU. SCC is a wave value, so the whole wave either skips the block or runs it. Each register the block writes merges at the branch target with a select on the condition under which the block runs: SCC for `s_cbranch_scc0`, the negated SCC for `s_cbranch_scc1`. The target must be a later instruction boundary, checked on real offsets. The block admits only the vector ALU forms that masked regions admit and `s_nop`. Memory, sampling, exports, waits, EXEC writes, scalar and wave updates, and nested branches or regions reject, as does a branch inside a masked region. An SCC from an ALU result rather than a compare also rejects. A VGPR first written in the block is undefined after it, including at the target, until an unconditional write defines it. SCC and VCC keep their tracked values across the block. `pixel_aot_scc_skip_{warp,hardware}` draws `s_cmp_eq_u32` + `s_cbranch_scc1` and `s_cmp_lg_u32` + `s_cbranch_scc0` with the runtime flag in constant word 6 set to 0, 1 and 7. An instruction after the target reads the merged value. The opposite polarity and a dropped branch must mismatch. On WARP 10.0.26100.9818 and an AMD Radeon RX 9070 XT (driver 32.0.31044.16), Windows 11 build 26300.9974, all six cases matched and all six mutant cases mismatched. LLVM 15 assembles and disassembles both labelled programs. + ```powershell cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^pixel_aot_exec_regions_(warp|hardware)$' -V diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 6032d1f48..8efba4d2c 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -278,6 +278,9 @@ def check_shader_records(): assert shift64_forms <= fc.gfx_forms(pixel.ACCEPTED, fc.load_reference(name)), name masked_forms = {("SOP1", "s_and_saveexec_b64"), ("SOPP", "s_cbranch_execz")} assert masked_forms <= fc.gfx_forms(pixel.ACCEPTED, gfx) + # Forward skips on a tracked scalar compare (issue #1413). + scc_skip_forms = {("SOPP", "s_cbranch_scc0"), ("SOPP", "s_cbranch_scc1")} + assert scc_skip_forms <= fc.gfx_forms(pixel.ACCEPTED, gfx) scalar64_forms = { ("SOP1", "s_cmov_b64"), ("SOP1", "s_not_b64"), ("SOP1", "s_brev_b64"), ("SOP2", "s_and_b64"), ("SOP2", "s_or_b64"), ("SOP2", "s_xor_b64"), @@ -349,7 +352,6 @@ def check_shader_records(): "v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16", "s_lshl0_add_u32", "s_lshl5_add_u32", "s_cbranch_execnz", "s_cbranch_vccz", "s_cbranch_vccnz", - "s_cbranch_scc0", "s_cbranch_scc1", "s_absdiff_i64", "s_absdiff_u32", "v_sad_u8", "v_sad_u16", "v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8", "v_mqsad_u32_u8", } diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 2403950e2..1cc8a1298 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -733,6 +733,119 @@ def check_masked_else_draw(directory, compiler, renderer, backend): run_pixel_batch(renderer, backend, shader, [(case, "mismatch")]) +# Uniform skips (issue #1413): a forward s_cbranch_scc0/scc1 on a tracked scalar compare jumps over a block of +# vector ALU. The flag in constant word 6 (s47) decides per draw whether the block runs. The block writes v13 and +# v14, and an instruction after the target reads the merged v14 into v15. +SCC_SKIP_FORMS = { + # name: (compare, branch); both skip the block exactly when s47 == 0. + "eq-scc1": ("s_cmp_eq_u32 s47, 0", "scc1"), + "lg-scc0": ("s_cmp_lg_u32 s47, 0", "scc0"), +} +SCC_SKIP_BODY = ("v_mov_b32_e32 v13, s45", "v_mov_b32_e32 v14, s46") +SCC_SKIP_AFTER = ("v_mul_f32_e32 v15, 0.5, v14",) + + +def scc_skip(compare="s_cmp_eq_u32 s47, 0", branch="scc1", body=SCC_SKIP_BODY, after=SCC_SKIP_AFTER, before=(), + target=None): + """The skip program as (offset, text) pairs; the branch lands on the first instruction after body unless + target names another displacement in dwords.""" + lines = uncompressed_export([*before, compare, f"s_cbranch_{branch} 0", *body, *after]) + pairs = offset_pairs(lines) + k = next(j for j, (_, line) in enumerate(pairs) if line.startswith("s_cbranch_scc")) + imm = (pairs[k + 1 + len(body)][0] - pairs[k][0] - 4) // 4 if target is None else target + pairs[k] = (pairs[k][0], f"s_cbranch_{branch} {imm}") + return pairs + + +def scc_skip_asm(compare, branch): + """scc_skip as assembler text: the branch names a label on its target.""" + program = [line for _, line in scc_skip(compare, branch)] + k = next(j for j, line in enumerate(program) if line.startswith("s_cbranch_scc")) + program[k] = f"s_cbranch_{branch} .Lscc_skip" + program.insert(k + 1 + len(SCC_SKIP_BODY), ".Lscc_skip:") + return program + + +def scc_skip_pixels(runs): + outer_b = single(128 / 255) + b = 0.75 if runs else outer_b + return [(single(r / 255), 0.25 if runs else single(g / 255), b, single(0.5 * b)) + for g in MASKED_RAMP for r in MASKED_RAMP] + + +def check_scc_skip_draw(directory, compiler, renderer, backend): + """Draw uniform skips (issue #1413) with the block taken and skipped, plus polarity and dropped-branch mutants.""" + source = directory / "scc.hlsl" + shader = directory / "scc.cso" + constants = bytearray(256) + + def case(name, flag, runs, outcome): + struct.pack_into("<3fI", constants, 12, 0.0, 0.25, 0.75, flag) + path = directory / f"scc-{name}-{flag}.case" + write_case(path, constants, scc_skip_pixels(runs)) + return path, outcome + + for name, (compare, branch) in SCC_SKIP_FORMS.items(): + source.write_text(translate(scc_skip(compare, branch)), encoding="ascii") + compile_shader(compiler, source, shader) + # s47 = 0 skips the block; 1 and 7 run it. + run_pixel_batch(renderer, backend, shader, + [case(name, 0, False, "pass"), case(name, 1, True, "pass"), case(name, 7, True, "pass")]) + flipped = {"scc0": "scc1", "scc1": "scc0"} + for name, (compare, branch) in SCC_SKIP_FORMS.items(): + mutants = ( + # The opposite polarity runs the block exactly when it should be skipped. + (f"{name}-polarity", scc_skip(compare, flipped[branch]), ((0, False), (1, True))), + # Without the branch the block always runs, which shows when the flag asks for the skip. + (f"{name}-dropped", uncompressed_export([compare, *SCC_SKIP_BODY, *SCC_SKIP_AFTER]), ((0, False),)), + ) + for label, program, flags in mutants: + source.write_text(translate(program), encoding="ascii") + compile_shader(compiler, source, shader) + run_pixel_batch(renderer, backend, shader, [case(label, flag, runs, "mismatch") for flag, runs in flags]) + + +def check_scc_skip_controls(): + """Issue #1413 stage 1: one forward SCC-led skip over vector ALU, merged with selects.""" + for name, (compare, branch) in SCC_SKIP_FORMS.items(): + source = translate(scc_skip(compare, branch)) + # The block runs under !SCC for scc1 and under SCC for scc0. + condition = "((!scc" if branch == "scc1" else "(scc" + assert f"_v13 = {condition}" in source and f"_v14 = {condition}" in source, name + assert "(0.5f * alu" in source, source # the instruction after the target reads the merged v14 + # The condition must be a tracked scalar compare. + expect_value_error(translate, scc_skip("s_and_b32 s60, s47, 1"), "Uniform branch requires a tracked scalar compare") + expect_value_error(translate, scc_skip("s_add_u32 s60, s47, 1"), "Uniform branch requires a tracked scalar compare") + translate(scc_skip("s_bitcmp1_b32 s47, 0")) + # The target is a later instruction boundary, checked on real offsets. + expect_value_error(translate, [line for _, line in scc_skip()], "Unsupported uniform branch") + for imm in (-1, -3, 400): + expect_value_error(translate, scc_skip(target=imm), "Uniform branch targets no later instruction boundary") + # Memory, EXEC, scalar and wave updates, waits and nesting stay out of the block. + for extra in ("image_sample v[16:19], v[8:9], s[28:35], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D", + "s_buffer_load_dword s70, s[44:47], 0x10", "s_mov_b32 s60, s45", "s_cmp_eq_u32 s45, s46", + "s_mov_b64 exec, s[60:61]", "s_and_saveexec_b64 s[60:61], vcc", "s_waitcnt lgkmcnt(0)", + "exp mrt0 v12, v13, v14, v15 done vm", "v_readfirstlane_b32 s62, v12"): + expect_value_error(translate, scc_skip(body=(*SCC_SKIP_BODY, extra)), + f"Instruction cannot run in a uniform skip block: {extra}") + nested = scc_skip(body=(*SCC_SKIP_BODY, "s_cbranch_scc1 0")) + expect_value_error(translate, nested, "Instruction cannot run in a uniform skip block: s_cbranch_scc1") + # Inside a masked region the branch is refused by the region gate. + expect_value_error(translate, offset_pairs(uncompressed_export([ + "s_cmp_eq_u32 s47, 0", "v_cmp_lt_f32_e64 vcc_lo, v12, s44", "s_and_saveexec_b64 s[60:61], vcc", + "s_cbranch_scc1 1", "v_mov_b32_e32 v13, s45", MASKED_OR_RESTORE])), + "Instruction cannot run in a masked region: s_cbranch_scc1 1") + # A VGPR first written in the block is undefined after it, also at the target, until written on every path. + for after in (("v_add_f32_e32 v13, v30, s45",), ("v_mov_b32_e32 v14, s46", "v_add_f32_e32 v13, v30, s45")): + expect_value_error(translate, scc_skip(body=("v_mov_b32_e32 v30, s45",), after=after), + "Read of a register defined only on the masked path") + translate(scc_skip(body=("v_mov_b32_e32 v30, s45",), after=("v_mov_b32_e32 v30, s46", "v_add_f32_e32 v13, v30, s45"))) + # The block writes no scalar state, so SCC and VCC keep their tracked values after it. + translate(scc_skip(after=("s_cselect_b32 s62, 1.0, 0", "v_mov_b32_e32 v15, s62"))) + # An empty block is a no-op skip. + translate(scc_skip(body=())) + + # v_cmpx regions (issue #932): `s_mov_b64 s[a:b], exec` saves the entry mask, a VOPC e32 v_cmpx intersects EXEC # with its comparison, and `s_mov_b64 exec, s[a:b]` (or `s_or_b64 exec, exec, s[a:b]`) closes the region. CMPX_SAVE = "s_mov_b64 s[60:61], exec" @@ -13427,6 +13540,7 @@ def check_controls(directory): check_masked_controls() check_masked_mov_close_controls() check_masked_else_controls() + check_scc_skip_controls() check_cmpx_controls() check_shift64_controls() check_region_body_controls() @@ -15571,6 +15685,8 @@ def check_binary(directory, assembler, objcopy, library): fixtures.append(([line for _, line in pairs], translate)) else: fixtures.append((else_region_asm(opener, restore, skips), translate, "gfx1013", "", pairs)) + for compare, branch in SCC_SKIP_FORMS.values(): + fixtures.append((scc_skip_asm(compare, branch), translate, "gfx1013", "", scc_skip(compare, branch))) fixtures.extend((program, translate) for program in ( cmpx_region(), cmpx_region(CMPX_OR_RESTORE), cmpx_observables(), *(cmpx_predicate_group(kind, first) for kind, first in CMPX_PREDICATE_GROUPS))) @@ -20668,7 +20784,7 @@ def main(): "draw-sad", "draw-int16-vop3", "draw-int16-ternary", "draw-compressed-export", "draw-uncompressed-export", "draw-uncompressed-integer-export", - "draw-title-loads", "draw-ds-swizzle", "draw-exec-regions", "draw-cmpx-regions", + "draw-title-loads", "draw-ds-swizzle", "draw-exec-regions", "draw-cmpx-regions", "draw-scc-skip", "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", "draw-f16-arith", "draw-f16-round", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", @@ -20709,6 +20825,7 @@ def main(): "draw-title-loads": check_title_load_draws, "draw-ds-swizzle": check_ds_swizzle_draw, "draw-exec-regions": check_masked_draw, + "draw-scc-skip": check_scc_skip_draw, "draw-cmpx-regions": check_cmpx_draw, "draw-region-body": check_region_body_draw, "draw-region-waits": check_region_wait_draw, diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 72a243015..b7cdfacd3 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -2924,6 +2924,10 @@ def close_region(i, pair): scc = None for i, (offset, line) in enumerate(positioned): + if region is not None and region["opener"] == "scc" and i == region["end"]: + # A uniform skip block ends where its branch lands, before that instruction runs and is checked. + close_region(i, None) + region = None vector.reads.clear() scalar.reads.clear() scalar.site = vector.site = (i, offset, line) @@ -2939,7 +2943,18 @@ def match(pattern): raise ValueError("ds_swizzle_b32 requires an immediate s_waitcnt lgkmcnt(0)") ds_needs_wait = False rstate = None - if region is not None: + if region is not None and region["opener"] == "scc": + # A uniform skip block (issue #1413) admits only per-lane vector ALU and s_nop: no memory, EXEC, + # scalar or wave updates and no nested branch or region. + if REGION_NOP.fullmatch(line): + pass + elif not REGION_ALU.match(line): + raise ValueError(f"Instruction cannot run in a uniform skip block: {line}") + else: + rstate = (dict(scalar), dict(vector), scc, set(pending), dict(sample_dest), + exported, ended, mask, attribute_input, interpolated, + dict(quad_values), samples, False) + elif region is not None: if re.fullmatch(r"s_or_b64 exec, exec, s\[\d+:\d+\]|s_mov_b64 exec, s\[\d+:\d+\]", line): pass elif re.fullmatch(r"s_andn2_b64 exec, s\[\d+:\d+\], exec", line): @@ -3246,6 +3261,26 @@ def match(pattern): "outstanding": (set(pending), dict(sample_dest))} vector.masked = True scalar.masked = True + elif m := match(r"s_cbranch_scc([01]) (-?0x[0-9a-f]+|-?\d+)"): + # A forward branch on a tracked scalar compare (issue #1413). SCC is a wave value, so the whole wave + # skips the block or runs it. The block's vector writes merge with a select on the condition under + # which it runs: SCC for s_cbranch_scc0, !SCC for s_cbranch_scc1. Offsets count from the next + # instruction, and the target must be a later instruction boundary. + if region is not None or mask != "entry" or offset is None: + raise ValueError("Unsupported uniform branch") + if not isinstance(scc, str) or not re.fullmatch(r"scc\d+", scc): + raise ValueError("Uniform branch requires a tracked scalar compare") + imm = int(m[2], 0) + if not -0x8000 <= imm <= 0x7fff: + raise ValueError("Uniform branch displacement out of range") + end = offset_index.get(offset + 4 + imm * 4) + if end is None or end <= i: + raise ValueError("Uniform branch targets no later instruction boundary") + region = {"save": None, "cond": scc if m[1] == "0" else f"(!{scc})", "written": {}, "skip": None, + "start": i, "arm_start": i, "else": None, "then": {}, "else_written": {}, + "else_undefined": set(), "skipped": False, "scalar_written": set(), "scc_written": False, + "opener": "scc", "end": end, "outstanding": (set(pending), dict(sample_dest))} + vector.masked = True elif m := match(r"s_cbranch_execz (-?0x[0-9a-f]+|-?\d+)"): # The whole-wave empty-mask skip may sit right after the save, or right after the else transition # (issue #1315); its target must be the matching restore exactly, or for the skip after the save of a From d2b9bcd6725bd2dabd1301ebea46f9410d9928b2 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 19:31:46 +0800 Subject: [PATCH 039/775] docs: distinguish local slot 70 logs from report summaries --- docs/experiments.md | 2 +- src/startup_stubs/memory_srv_report.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 82584f9dd..8facc5e75 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9471,7 +9471,7 @@ line, for the first eight refusals of a process (stderr and `X2W_TRAP_LOG`). The check that refused it, in the order the checks run: `null_destination`, `unreadable_resource`, `unreadable_view`, `null_address`, `unsupported_description`, `destination_outside_view_heaps`, or `texture_unavailable` (the description passed but no single live texture or published view matches the -address). It then prints what the checks read: resource dimension, format, width by height by depth or +address). Keep full logs from private inputs local. In public reports, give the reason and general resource/view categories. Use source-built inputs for full diagnostic lines. The line prints what the checks read: resource dimension, format, width by height by depth or array size, mips, layout, flags, alignment and sample count and quality; view dimension, format and component mapping, with the mip, plane and array fields for 2D and 2D-array views and the first element, count, stride and flags for buffer views (any other dimension prints its six raw words); diff --git a/src/startup_stubs/memory_srv_report.h b/src/startup_stubs/memory_srv_report.h index a6f04d97a..ff74b82b2 100644 --- a/src/startup_stubs/memory_srv_report.h +++ b/src/startup_stubs/memory_srv_report.h @@ -1,8 +1,8 @@ // Experimental (docs/startup-runtime.md): one compact diagnostic line for a refused device slot 70 // call (a shader resource view whose resource is an address). // -// The line names the first check that refused the call and the fields the checks read, so a tester -// can paste it into an issue: the resource description, the view description, the destination handle +// The line names the first check that refused the call and the fields the checks read, for +// local diagnosis: the resource description, the view description, the destination handle // and whether it lies in a known CBV/SRV/UAV heap, and the address and whether it is readable. It is // formatted into a caller-supplied fixed buffer and allocates nothing. A null resource or view pointer // means the guest memory could not be read; its fields are then shown as "unreadable". From d187362408124c5988392fcad84eeacb29bbd596 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 19:27:39 +0800 Subject: [PATCH 040/775] shader: lower gfx1030 2D image LOD queries --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 5 ++ README.md | 1 + docs/experiments.md | 21 +++++++ tests/pixel_get_lod_check.py | 114 ++++++++++++++++++++++++++++++++++ tools/pixel_aot.py | 27 ++++++++ 6 files changed, 169 insertions(+) create mode 100644 tests/pixel_get_lod_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b73d82490..424ea57a1 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -44,6 +44,7 @@ jobs: python3 -B tests/mesh_entry_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/mesh_descriptor_swap_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/mesh_lit_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 + python3 -B tests/pixel_get_lod_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/mesh_shadow_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/ffx_dispatch_aot_check.py llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/startup_sampler_heap_check.py binary llvm-mc-15 diff --git a/CMakeLists.txt b/CMakeLists.txt index 820ccc686..28db75433 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5726,6 +5726,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_comparisons_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_comparisons_${adapter}.txt") + add_test(NAME pixel_aot_get_lod_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_get_lod_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_get_lod_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_get_lod_${adapter}.txt") add_test(NAME pixel_aot_blend_scalar_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-blend-scalar "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 75dad6a6e..92d252cd6 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 formatted UINT buffer writes | Lower [indexed `buffer_store_format_*` with matching caller-declared UINT texels](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-writes) and compare full UAV readback with a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | Shader census | [Distinguish archive records, header digests and cache-index entries](docs/experiments.md#reporting-shader-census-populations) before choosing a coverage denominator. | `ctest --preset dev --no-tests=error -R "^shader_metadata_census$" -V` | | Shader effect metadata | Inventory the [candidate programs for a named SGD5 effect](docs/experiments.md#candidate-programs-for-a-named-sgd5-effect) using independently located archive ranges. | `ctest --preset dev --no-tests=error -R "^sgd5_effect_candidates$" -V` | +| gfx1030 image LOD query | Lower [clamped and raw 2D LOD queries](docs/experiments.md#gfx1030-2d-image-lod-queries) for `image_get_lod` in pixel shaders. | `ctest --preset dev --no-tests=error -R '^pixel_aot_get_lod_'` | | Pipeline readiness | Join explicit pipeline references to the native shader manifest and optionally probe pixel and mesh lowering. [Inputs and WARP control](docs/experiments.md#pipeline-readiness-from-shader-manifests) | `ctest --preset dev -R '^pso_' -V` | | D3D12 and ray tracing | Compare the CPU reference, custom BVH shader and DXR on another adapter. Record the driver and native wave width. | `ctest --preset dev -R '^bvh_(differential\|wave64)_hardware$' -V` | | Upscaler memory accounting | Compare [post-query counter writes](docs/experiments.md#upscaler-working-set-counter-updates) on success and failure. | `ctest --preset dev --no-tests=error -R 'working_set_delta$'` | diff --git a/docs/experiments.md b/docs/experiments.md index 74731611c..fa026b750 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -678,6 +678,27 @@ foreach ($adapter in 'hardware','warp') { } ``` +### gfx1030 2D image LOD queries + +The pixel translator lowers `image_get_lod` for a single 2D texture and an +ordinary sampler. It accepts a contiguous pair of 32-bit UVs with quad +provenance and `dmask:0x3`. The results are the sampler-clamped LOD followed +by the raw LOD. A matching image and sampler descriptor must be ready before +the query. Both result registers need `s_waitcnt vmcnt(0)` before use. + +The fixture draws an 8 by 8 viewport over a single-mip 8 by 8 texture. The +CPU reference derives raw LOD from four power-of-two UV scales and compares +all exported channels, including the clamped LOD of zero. Clamping the raw +result first differs at pixel `(0, 0)`, channel 1 (`-1` expected, `0` actual). +A two-mip draw also checks clamped LOD 1 and raw LOD 2. Removing the upper +clamp gives 2 in the channel that should contain 1. LLVM 15 assembles both +gfx1030 programs and round-trips them through the pixel container CLI. The GPU fixture executes the translated desktop DXIL. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^pixel_aot_get_lod_(warp|hardware)$' -V +``` + ### Unsigned pixel conversion and entry inputs The plain gfx1013 `v_cvt_u32_f32_e32` path uses the binary32-to-uint helper from the FFX translator. It truncates positive fractions toward zero, maps NaN and negative inputs to zero, and saturates at `0xffffffff` for inputs at or above 2^32. Sources are a defined VGPR, a ready SGPR or a hexadecimal literal word. Whole-quad execution requires a source defined for helper lanes. A varying conversion cannot establish an affine texture coordinate. [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) · [Shared conversion implementation](../src/ffx_float_to_int.hlsli) diff --git a/tests/pixel_get_lod_check.py b/tests/pixel_get_lod_check.py new file mode 100644 index 000000000..b9fb0e51f --- /dev/null +++ b/tests/pixel_get_lod_check.py @@ -0,0 +1,114 @@ +"""Check both gfx1030 image_get_lod results against a CPU footprint model.""" +import math +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import assemble +from pixel_aot_check import envelope, pixel_aot, translate, write_record +from pixel_sample_lod_check import base_prefix, compile_ps + + +QUERY = "image_get_lod v[12:13], v[8:9], s[28:35], s[40:43] dmask:0x3 dim:SQ_RSRC_IMG_2D" + + +def program(): + lines = base_prefix(quad_scale=True) + i = lines.index("v_fma_f32 v8, s62, v8, 0") + lines.insert(i + 1, "v_fma_f32 v9, s63, v9, 0") + return lines + [QUERY, "s_waitcnt vmcnt(0)", "v_mov_b32_e32 v14, 0.5", "v_mov_b32_e32 v15, 1.0", + "exp mrt0 v12, v13, v14, v15 done vm", "s_endpgm"] + + +def upper_clamp_program(): + # On the two-mip fixture, the horizontal UV scale is 4. Export raw LOD - 2 in + # red and clamped LOD in green, so the expected color is (0, 1, 0, 1). + return base_prefix(quad_scale=True) + [ + QUERY, "s_waitcnt vmcnt(0)", "v_subrev_f32_e32 v13, 2.0, v13", + "v_mov_b32_e32 v14, 0", "v_mov_b32_e32 v15, 1.0", + "exp mrt0 v13, v12, v14, v15 done vm", "s_endpgm", + ] + + +def controls(): + for old, new, diagnostic in ( + ("s_waitcnt vmcnt(0)", "s_nop 0", "Unsupported export"), + ("s[40:43] dmask", "s[44:47] dmask", "Unsupported texture LOD image or sampler binding"), + ("dmask:0x3", "dmask:0xf", "Unsupported instruction"), + ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_3D", "Unsupported instruction"), + (QUERY, "v_mov_b32_e32 v8, 0.5\n" + QUERY, "quad provenance"), + ): + changed = [part for line in program() for part in line.replace(old, new).splitlines()] + try: + translate(changed) + except ValueError as error: + assert diagnostic.casefold() in str(error).casefold(), str(error) + else: + raise AssertionError(f"Expected rejection: {diagnostic}") + + +def binary(directory, assembler, objcopy, library): + for stem, lines in (("footprint", program()), ("upper-clamp", upper_clamp_program())): + native = assemble(directory, assembler, objcopy, lines, cpu="gfx1030", features="+wavefrontsize64") + decoded = pixel_aot.disassemble(native, library, cpu=b"gfx1030", features=b"+wavefrontsize64", offsets=True) + assert [line for _, line in decoded if line.startswith("image_")] == [QUERY] + expected = translate(lines) + assert translate(decoded) == expected + archive, result = directory / f"{stem}.rpf", directory / f"{stem}-cli.hlsl" + archive.write_bytes(envelope(native)) + subprocess.run([sys.executable, "-B", pixel_aot.__file__, archive, "fixture", "--llvm", library, + "--texture-sgpr", "20", "--interp-sgpr", "24", "--sampler-words", "1", "2", "3", "4", + "--constant-descriptor", "0x40", "--output", result], check=True) + assert result.read_text() == expected + controls() + return 0 + + +def draw(directory, compiler, renderer, backend): + controls() + source = translate(program()) + cso = compile_ps(compiler, source, directory, "lod") + case = directory / "lod.case" + command = [renderer, backend, "--check-pixel-case", cso, case] + for scale in (0.5, 0.25, 1.0, 2.0): + raw_lod = math.log2(scale) + # The viewport and texture are both 8x8. The point sampler has MinLOD=0, + # and the view has one mip. Negative derivative LODs must remain negative in Y. + reference = struct.pack("<4f", 0, raw_lod, 0.5, 1) + case.write_bytes(struct.pack("<4f", 0, 0, scale, scale) + bytes(240) + reference * 64 + struct.pack(" 256 or coords.stop > 256: + raise ValueError("Texture LOD VGPR out of range") + if any(f"v{n}" in sample_dest for n in dest): + raise ValueError("Write overlaps an outstanding sample") + descriptor = [scalar.get(f"s{n}") for n in image] + if (mask != "entry" or sampler is None or sample_kind == "comparison" + or second_texture_offset is not None + or descriptor != [(bindings[texture_offset], j) for j in range(8)] + or any(f"s{n}" in pending for n in (*image, *state)) + or [scalar.get(f"s{n}") for n in state] != list(sampler)): + raise ValueError("Unsupported texture LOD image or sampler binding") + uv = [vector.get(f"v{n}") for n in coords] + if any(value not in quad_values for value in uv): + raise ValueError("Texture LOD requires coordinates with quad provenance") + coord = f"float2({', '.join(uv)})" + lines.append(f" float2 sample{i} = float2(tex.CalculateLevelOfDetail(samp, {coord}), " + f"tex.CalculateLevelOfDetailUnclamped(samp, {coord}));") + sample_kind = "plain" + samples += 1 + vector_loads += 1 + for channel, n in zip("xy", dest): + vector[f"v{n}"] = f"sample{i}.{channel}" + sample_dest[f"v{n}"] = vector_loads elif m := match(r"(flat|global)_load_dword (v\d+), v\[(\d+):(\d+)\](, off)?(?: offset:(-?\d+))?"): # One DWORD through a 64-bit title address. Cache-policy bits, the global saddr form and # every other width or direction are refused by the fall-through. From 59ed0a5a0a49bbb8f78345a98c6821a982b95d43 Mon Sep 17 00:00:00 2001 From: ammar Date: Tue, 24 Nov 2026 13:32:24 +0200 Subject: [PATCH 041/775] cpu: lift SSE4a extrq, insertq, movntsd, and movntss leaf functions --- CMakeLists.txt | 23 ++ docs/experiments.md | 21 ++ tests/cpu/sse4a.asm | 511 +++++++++++++++++++++++++++ tests/cpu/sse4a.def | 47 +++ tests/cpu/sse4a_check.py | 743 +++++++++++++++++++++++++++++++++++++++ tools/cpu_sse4a_aot.py | 373 ++++++++++++++++++++ 6 files changed, 1718 insertions(+) create mode 100644 tests/cpu/sse4a.asm create mode 100644 tests/cpu/sse4a.def create mode 100644 tests/cpu/sse4a_check.py create mode 100644 tools/cpu_sse4a_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 820ccc686..025760f1c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2395,6 +2395,29 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(cpu_aot_pcmpstr64 PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_pcmpstr64.txt") + set(cpu_sse4a_exports + "op_extrq_imm_basic,op_extrq_imm_zero_len,op_extrq_imm_high_bit," + "op_extrq_imm_mid,op_extrq_imm_bits76," + "op_extrq_reg_basic,op_extrq_reg_self,op_extrq_reg_xmm4_xmm5," + "op_insertq_imm_basic,op_insertq_imm_zero_len,op_insertq_imm_high_bit," + "op_insertq_imm_self," + "op_insertq_reg_basic,op_insertq_reg_self,op_insertq_reg_xmm4_xmm5," + "op_movntsd_aligned,op_movntsd_disp8,op_movntsd_unaligned," + "op_movntss_aligned,op_movntss_disp12,op_movntss_unaligned," + "op_pipeline,op_discarded_read,op_sse4a_discarded_read") + string(CONCAT cpu_sse4a_exports ${cpu_sse4a_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_sse4a_${variant} sse4a) + cpu_translation(cpu_sse4a_${variant} cpu_sse4a_aot "${cpu_sse4a_exports}") + endforeach() + target_compile_definitions(cpu_sse4a_altered PRIVATE ALTER_IMM) + add_test(NAME cpu_aot_sse4a COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sse4a_check.py" + "$" + "$" + "$") + set_tests_properties(cpu_aot_sse4a PROPERTIES + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_sse4a.txt") set(cpu_sse2_exports "op_cmppd_0,op_cmppd_1,op_cmppd_2,op_cmppd_3,op_cmppd_4,op_cmppd_5,op_cmppd_6,op_cmppd_7," "op_cmppd_mem," diff --git a/docs/experiments.md b/docs/experiments.md index 74731611c..5ea1e2dbc 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9603,3 +9603,24 @@ For the same nine-mip textures, slot 2 returns the byte offset of each mip withi cmake --build --preset release --target startup_stream_consumer startup_stub_xg_xs xg_swizzle_select_check ctest --preset release --no-tests=error --output-on-failure -R '^(startup_xg_bc_(array|chain)_(hardware|warp)|startup_xg_bc_tiling|xg_bc64_tiling_reference|startup_xg_bc7_layout)$' ``` + +## SSE4a bit-field and non-temporal scalar store leaf recompilation + +[The SSE4a leaf translator](../tools/cpu_sse4a_aot.py) lifts bounded straight-line Windows x64 leaf functions covering the six SSE4a instruction forms across the four mnemonics in `docs/coverage/x64_zen2.tsv` group `SSE3-4`: + +- `extrq` (immediate form `66 0F 78 /0 ib ib` and register form `66 0F 79 /r`): extracts a bit field of width `len & 0x3f` (`0` means `64`) at bit offset `idx & 0x3f` from `xmm[63:0]` and zero-extends into `xmm[63:0]` (register control read from `xmm2[5:0]` and `xmm2[13:8]`). +- `insertq` (immediate form `F2 0F 78 /r ib ib` and register form `F2 0F 79 /r`): inserts the low `width` bits of `xmm2[63:0]` at `offset` in `xmm1[63:0]` while preserving the remaining bits of `xmm1[63:0]` (register control read from `xmm2[69:64]` and `xmm2[77:72]`). +- `movntsd` (`F2 0F 2B /r`) and `movntss` (`F3 0F 2B /r`): unaligned 64-bit and 32-bit stores from `xmm[63:0]` / `xmm[31:0]` to flat `[r8 + disp]` destinations. + +Each lifted export takes `(word rcx, word rdx, word r8)` pointing to caller-owned flat buffers (`rcx` and `rdx` inputs, `r8` output) and returns `void`. Register state covers volatile `xmm0`..`xmm5` modeled as `Vec128` (`std::uint64_t q[2]`). Architecturally undefined bits `127:64` after `extrq`/`insertq` are left untouched in the model and not observed by tests. Transport and ABI glue covers `movaps`, `movdqa` (16-byte aligned), `movdqu` (unaligned), and terminal `ret`. The translator rejects static `offset + width > 64` on immediate `extrq`/`insertq`, invalid `extrq /1` encodings, VEX/EVEX non-legacy encodings, nonvolatile `xmm6`..`xmm15` or nonvolatile GPR bases, non-`r8` store bases, unaligned 16-byte `movaps`/`movdqa` operands, undefined register reads, prefixes, unsupported instructions, missing `ret`, and instructions after `ret`. + +```powershell +cmake --build --preset dev --target cpu_sse4a_original cpu_sse4a_original_lifted cpu_sse4a_altered cpu_sse4a_altered_lifted +ctest --preset dev --no-tests=error -R '^cpu_aot_sse4a$' -V +``` + +### Measured results and open scope + +The [MASM fixture](../tests/cpu/sse4a.asm) exports 24 translated `op_*` functions covering immediate and register `extrq`/`insertq` (including `length=0` meaning `64`, bits `[7:6]`/`[15:14]` ignored, self-aliasing, and `xmm4`/`xmm5`), aligned and unaligned `movntsd`/`movntss`, a chained `op_pipeline`, and two dead-read fault-ordering controls (`op_discarded_read` and `op_sse4a_discarded_read`), alongside 22 Win64 MASM baseline `ref_*` exports so verification runs on both Intel and AMD hosts without skipping. [The differential check](../tests/cpu/sse4a_check.py) verifies 580 cases across the 22 differential exports bit-for-bit across `dev` and `release` (`/O2`) builds against both the independent Python AMD64 APM reference model and the Win64 MASM `ref_*` baseline (and cross-checks native `op_*` execution when `CPUID.80000001H:ECX[6]` is set), with 32-byte pre/post buffer guards, dead-read fault ordering, 6 `ALTER_IMM` divergence controls (minimum 7 differing cases), an output-mutation control, 6 alternate-encoding lift checks, 54 unit rejection controls, and 11 PE-patched DLL rejection controls. It also records decoded mnemonics of the translated exports through `FORM_COVERAGE_RECORD`. + +Not covered by this experiment: non-temporal cache-bypass hints, runtime `offset + width > 64` hardware-undefined behavior in register-form `extrq`/`insertq`, control flow or nonvolatile prologues, and title CPU code execution. diff --git a/tests/cpu/sse4a.asm b/tests/cpu/sse4a.asm new file mode 100644 index 000000000..6f6ec2ea2 --- /dev/null +++ b/tests/cpu/sse4a.asm @@ -0,0 +1,511 @@ +; coverage: record cpu_aot_sse4a +; Source-built MASM fixture exercising all 6 SSE4a forms (extrq imm/reg, +; insertq imm/reg, movntsd, movntss) from docs/coverage/x64_zen2.tsv group +; SSE3-4, along with Win64 MASM baseline ref_* exports so lifted verification +; always runs on both Intel and AMD hosts. +; Every export uses the Windows x64 leaf ABI: +; RCX = const void* input_a (32 bytes, 16-byte aligned) +; RDX = const void* input_b (32 bytes, 16-byte aligned) +; R8 = void* output (32 bytes, 16-byte aligned) + +; Helper macro: rax = extrq(rax, r9[13:0]) with width=0 -> 64. Clobbers rcx, r10. +REF_EXTRQ MACRO + LOCAL done_mask + mov ecx, r9d + and ecx, 3Fh + mov r10, -1 + jz done_mask + mov r10, 1 + shl r10, cl + dec r10 +done_mask: + mov ecx, r9d + shr ecx, 8 + and ecx, 3Fh + shr rax, cl + and rax, r10 +ENDM + +; Helper macro: rax = insertq(rax, r11, r9[13:0]) with width=0 -> 64. Clobbers rcx, r10, r11. +REF_INSERTQ MACRO + LOCAL done_mask + mov ecx, r9d + and ecx, 3Fh + mov r10, -1 + jz done_mask + mov r10, 1 + shl r10, cl + dec r10 +done_mask: + and r11, r10 + mov ecx, r9d + shr ecx, 8 + and ecx, 3Fh + shl r10, cl + shl r11, cl + not r10 + and rax, r10 + or rax, r11 +ENDM + +.code + +; --- extrq immediate form (66 0F 78 /0 ib ib) --- + +op_extrq_imm_basic PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] +IFDEF ALTER_IMM + extrq xmm0, 12, 24 +ELSE + extrq xmm0, 12, 20 +ENDIF + movntsd QWORD PTR [r8], xmm0 + ret +op_extrq_imm_basic ENDP + +op_extrq_imm_zero_len PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] +IFDEF ALTER_IMM + extrq xmm0, 63, 0 +ELSE + extrq xmm0, 0, 0 +ENDIF + movntsd QWORD PTR [r8], xmm0 + ret +op_extrq_imm_zero_len ENDP + +op_extrq_imm_high_bit PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + extrq xmm0, 1, 63 + movntsd QWORD PTR [r8], xmm0 + ret +op_extrq_imm_high_bit ENDP + +op_extrq_imm_mid PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + extrq xmm1, 16, 48 + movntsd QWORD PTR [r8], xmm1 + ret +op_extrq_imm_mid ENDP + +op_extrq_imm_bits76 PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + extrq xmm0, 48h, 05h + movntsd QWORD PTR [r8], xmm0 + ret +op_extrq_imm_bits76 ENDP + +; --- extrq register form (66 0F 79 /r) --- + +op_extrq_reg_basic PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + extrq xmm0, xmm1 + movntsd QWORD PTR [r8], xmm0 + ret +op_extrq_reg_basic ENDP + +op_extrq_reg_self PROC FRAME + .endprolog + movaps xmm2, XMMWORD PTR [rcx] + extrq xmm2, xmm2 + movntsd QWORD PTR [r8], xmm2 + ret +op_extrq_reg_self ENDP + +op_extrq_reg_xmm4_xmm5 PROC FRAME + .endprolog + movdqa xmm4, XMMWORD PTR [rcx+16] + movdqu xmm5, XMMWORD PTR [rdx+1] + extrq xmm4, xmm5 + movntsd QWORD PTR [r8], xmm4 + ret +op_extrq_reg_xmm4_xmm5 ENDP + +; --- insertq immediate form (F2 0F 78 /r ib ib) --- + +op_insertq_imm_basic PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_IMM + insertq xmm0, xmm1, 16, 20 +ELSE + insertq xmm0, xmm1, 16, 16 +ENDIF + movntsd QWORD PTR [r8], xmm0 + ret +op_insertq_imm_basic ENDP + +op_insertq_imm_zero_len PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_IMM + insertq xmm0, xmm1, 63, 0 +ELSE + insertq xmm0, xmm1, 0, 0 +ENDIF + movntsd QWORD PTR [r8], xmm0 + ret +op_insertq_imm_zero_len ENDP + +op_insertq_imm_high_bit PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + insertq xmm0, xmm1, 1, 63 + movntsd QWORD PTR [r8], xmm0 + ret +op_insertq_imm_high_bit ENDP + +op_insertq_imm_self PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + insertq xmm0, xmm0, 12, 36 + movntsd QWORD PTR [r8], xmm0 + ret +op_insertq_imm_self ENDP + +; --- insertq register form (F2 0F 79 /r) --- + +op_insertq_reg_basic PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + insertq xmm0, xmm1 + movntsd QWORD PTR [r8], xmm0 + ret +op_insertq_reg_basic ENDP + +op_insertq_reg_self PROC FRAME + .endprolog + movaps xmm3, XMMWORD PTR [rcx] + insertq xmm3, xmm3 + movntsd QWORD PTR [r8], xmm3 + ret +op_insertq_reg_self ENDP + +op_insertq_reg_xmm4_xmm5 PROC FRAME + .endprolog + movdqa xmm4, XMMWORD PTR [rcx+16] + movdqu xmm5, XMMWORD PTR [rdx+1] + insertq xmm4, xmm5 + movntsd QWORD PTR [r8], xmm4 + ret +op_insertq_reg_xmm4_xmm5 ENDP + +; --- movntsd (F2 0F 2B /r) and movntss (F3 0F 2B /r) --- + +op_movntsd_aligned PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movntsd QWORD PTR [r8], xmm0 + ret +op_movntsd_aligned ENDP + +op_movntsd_disp8 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_IMM + movntsd QWORD PTR [r8+16], xmm1 +ELSE + movntsd QWORD PTR [r8+8], xmm1 +ENDIF + ret +op_movntsd_disp8 ENDP + +op_movntsd_unaligned PROC FRAME + .endprolog + movdqu xmm0, XMMWORD PTR [rcx+3] + movntsd QWORD PTR [r8+1], xmm0 + ret +op_movntsd_unaligned ENDP + +op_movntss_aligned PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movntss DWORD PTR [r8], xmm0 + ret +op_movntss_aligned ENDP + +op_movntss_disp12 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_IMM + movntss DWORD PTR [r8+16], xmm1 +ELSE + movntss DWORD PTR [r8+12], xmm1 +ENDIF + ret +op_movntss_disp12 ENDP + +op_movntss_unaligned PROC FRAME + .endprolog + movdqu xmm0, XMMWORD PTR [rcx+5] + movntss DWORD PTR [r8+3], xmm0 + ret +op_movntss_unaligned ENDP + +; --- Chained pipeline and discarded-read fault ordering --- + +op_pipeline PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + movdqa xmm2, XMMWORD PTR [rcx+16] + movdqu xmm3, XMMWORD PTR [rdx+16] + extrq xmm0, 16, 8 + insertq xmm2, xmm0, 16, 24 + insertq xmm2, xmm1 + extrq xmm3, xmm1 + movntsd QWORD PTR [r8], xmm2 + movntsd QWORD PTR [r8+8], xmm3 + movntss DWORD PTR [r8+16], xmm0 + movntss DWORD PTR [r8+21], xmm2 + ret +op_pipeline ENDP + +; Universal native+lifted dead-read ordering control (runs on Intel & AMD). +op_discarded_read PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps XMMWORD PTR [r8], xmm0 + movaps xmm5, XMMWORD PTR [rdx] + movaps XMMWORD PTR [r8+16], xmm0 + ret +op_discarded_read ENDP + +; SSE4a dead-read ordering control (lifted always; native gated on CPUID SSE4a). +op_sse4a_discarded_read PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movntsd QWORD PTR [r8], xmm0 + movdqu xmm5, XMMWORD PTR [rdx] + extrq xmm5, 8, 8 + movntss DWORD PTR [r8+8], xmm0 + ret +op_sse4a_discarded_read ENDP + +; --- Win64 MASM baseline reference exports (never translated; run on Intel & AMD) --- + +ref_extrq_imm_basic PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r9d, (20 SHL 8) OR 12 + REF_EXTRQ + mov QWORD PTR [r8], rax + ret +ref_extrq_imm_basic ENDP + +ref_extrq_imm_zero_len PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r9d, 0 + REF_EXTRQ + mov QWORD PTR [r8], rax + ret +ref_extrq_imm_zero_len ENDP + +ref_extrq_imm_high_bit PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r9d, (63 SHL 8) OR 1 + REF_EXTRQ + mov QWORD PTR [r8], rax + ret +ref_extrq_imm_high_bit ENDP + +ref_extrq_imm_mid PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r9d, (48 SHL 8) OR 16 + REF_EXTRQ + mov QWORD PTR [r8], rax + ret +ref_extrq_imm_mid ENDP + +ref_extrq_imm_bits76 PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r9d, (05h SHL 8) OR 48h + REF_EXTRQ + mov QWORD PTR [r8], rax + ret +ref_extrq_imm_bits76 ENDP + +ref_extrq_reg_basic PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r9, QWORD PTR [rdx] + REF_EXTRQ + mov QWORD PTR [r8], rax + ret +ref_extrq_reg_basic ENDP + +ref_extrq_reg_self PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r9, rax + REF_EXTRQ + mov QWORD PTR [r8], rax + ret +ref_extrq_reg_self ENDP + +ref_extrq_reg_xmm4_xmm5 PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx+16] + mov r9, QWORD PTR [rdx+1] + REF_EXTRQ + mov QWORD PTR [r8], rax + ret +ref_extrq_reg_xmm4_xmm5 ENDP + +ref_insertq_imm_basic PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r11, QWORD PTR [rdx] + mov r9d, (16 SHL 8) OR 16 + REF_INSERTQ + mov QWORD PTR [r8], rax + ret +ref_insertq_imm_basic ENDP + +ref_insertq_imm_zero_len PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r11, QWORD PTR [rdx] + mov r9d, 0 + REF_INSERTQ + mov QWORD PTR [r8], rax + ret +ref_insertq_imm_zero_len ENDP + +ref_insertq_imm_high_bit PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r11, QWORD PTR [rdx] + mov r9d, (63 SHL 8) OR 1 + REF_INSERTQ + mov QWORD PTR [r8], rax + ret +ref_insertq_imm_high_bit ENDP + +ref_insertq_imm_self PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r11, rax + mov r9d, (36 SHL 8) OR 12 + REF_INSERTQ + mov QWORD PTR [r8], rax + ret +ref_insertq_imm_self ENDP + +ref_insertq_reg_basic PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r11, QWORD PTR [rdx] + mov r9, QWORD PTR [rdx+8] + REF_INSERTQ + mov QWORD PTR [r8], rax + ret +ref_insertq_reg_basic ENDP + +ref_insertq_reg_self PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov r11, rax + mov r9, QWORD PTR [rcx+8] + REF_INSERTQ + mov QWORD PTR [r8], rax + ret +ref_insertq_reg_self ENDP + +ref_insertq_reg_xmm4_xmm5 PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx+16] + mov r11, QWORD PTR [rdx+1] + mov r9, QWORD PTR [rdx+9] + REF_INSERTQ + mov QWORD PTR [r8], rax + ret +ref_insertq_reg_xmm4_xmm5 ENDP + +ref_movntsd_aligned PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx] + mov QWORD PTR [r8], rax + ret +ref_movntsd_aligned ENDP + +ref_movntsd_disp8 PROC FRAME + .endprolog + mov rax, QWORD PTR [rdx] + mov QWORD PTR [r8+8], rax + ret +ref_movntsd_disp8 ENDP + +ref_movntsd_unaligned PROC FRAME + .endprolog + mov rax, QWORD PTR [rcx+3] + mov QWORD PTR [r8+1], rax + ret +ref_movntsd_unaligned ENDP + +ref_movntss_aligned PROC FRAME + .endprolog + mov eax, DWORD PTR [rcx] + mov DWORD PTR [r8], eax + ret +ref_movntss_aligned ENDP + +ref_movntss_disp12 PROC FRAME + .endprolog + mov eax, DWORD PTR [rdx] + mov DWORD PTR [r8+12], eax + ret +ref_movntss_disp12 ENDP + +ref_movntss_unaligned PROC FRAME + .endprolog + mov eax, DWORD PTR [rcx+5] + mov DWORD PTR [r8+3], eax + ret +ref_movntss_unaligned ENDP + +ref_pipeline PROC FRAME + .endprolog + movq xmm0, QWORD PTR [rcx+16] ; save a_hi before REF_EXTRQ clobbers rcx + ; Step 1: xmm0 = extrq(a_lo, 16, 8) -> low 32 bits go to [r8+16] + mov rax, QWORD PTR [rcx] + mov r9d, (8 SHL 8) OR 16 + REF_EXTRQ + mov DWORD PTR [r8+16], eax + mov r11, rax + ; Step 2: xmm2 = insertq(a_hi, xmm0, 16, 24) + movq rax, xmm0 + mov r9d, (24 SHL 8) OR 16 + REF_INSERTQ + ; Step 3: xmm2 = insertq(xmm2, xmm1) + mov r11, QWORD PTR [rdx] + mov r9, QWORD PTR [rdx+8] + REF_INSERTQ + mov QWORD PTR [r8], rax + mov r11, rax ; keep xmm2[31:0] for [r8+21] + ; Step 4: xmm3 = extrq(b_hi, xmm1) + mov rax, QWORD PTR [rdx+16] + mov r9, QWORD PTR [rdx] + REF_EXTRQ + mov QWORD PTR [r8+8], rax + ; Step 5: movntss [r8+21], xmm2 + mov DWORD PTR [r8+21], r11d + ret +ref_pipeline ENDP + +END diff --git a/tests/cpu/sse4a.def b/tests/cpu/sse4a.def new file mode 100644 index 000000000..b746a4744 --- /dev/null +++ b/tests/cpu/sse4a.def @@ -0,0 +1,47 @@ +EXPORTS + op_extrq_imm_basic + op_extrq_imm_zero_len + op_extrq_imm_high_bit + op_extrq_imm_mid + op_extrq_imm_bits76 + op_extrq_reg_basic + op_extrq_reg_self + op_extrq_reg_xmm4_xmm5 + op_insertq_imm_basic + op_insertq_imm_zero_len + op_insertq_imm_high_bit + op_insertq_imm_self + op_insertq_reg_basic + op_insertq_reg_self + op_insertq_reg_xmm4_xmm5 + op_movntsd_aligned + op_movntsd_disp8 + op_movntsd_unaligned + op_movntss_aligned + op_movntss_disp12 + op_movntss_unaligned + op_pipeline + op_discarded_read + op_sse4a_discarded_read + ref_extrq_imm_basic + ref_extrq_imm_zero_len + ref_extrq_imm_high_bit + ref_extrq_imm_mid + ref_extrq_imm_bits76 + ref_extrq_reg_basic + ref_extrq_reg_self + ref_extrq_reg_xmm4_xmm5 + ref_insertq_imm_basic + ref_insertq_imm_zero_len + ref_insertq_imm_high_bit + ref_insertq_imm_self + ref_insertq_reg_basic + ref_insertq_reg_self + ref_insertq_reg_xmm4_xmm5 + ref_movntsd_aligned + ref_movntsd_disp8 + ref_movntsd_unaligned + ref_movntss_aligned + ref_movntss_disp12 + ref_movntss_unaligned + ref_pipeline diff --git a/tests/cpu/sse4a_check.py b/tests/cpu/sse4a_check.py new file mode 100644 index 000000000..51b7ee510 --- /dev/null +++ b/tests/cpu/sse4a_check.py @@ -0,0 +1,743 @@ +"""Differential checks, ALTER_IMM/mutation controls and rejection controls for SSE4a AOT. + +Verification always runs on both Intel and AMD hosts without skipping: + - Lifted exports (cpu_sse4a_original_lifted) are compared bit-for-bit against both + an independent Python AMD64 APM reference model and Win64 MASM baseline ref_* + exports (cpu_sse4a_original). + - When CPUID.80000001H:ECX[6] reports native SSE4a support, the native op_* + exports in cpu_sse4a_original are also executed and cross-checked bit-for-bit. +""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import sys +from tempfile import TemporaryDirectory + +import pefile +from iced_x86 import ( + Code, + Decoder, + Encoder, + Formatter, + FormatterSyntax, + Instruction, + MemoryOperand, + Register as R, +) + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva +from cpu_sse4a_aot import lift_code, translate + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(0xA0 + (i % 16) for i in range(32)) +GUARD_POST = bytes(0xC0 + (i % 16) for i in range(32)) +FILL = b"\x5A" * 32 + +DIFF_EXPORTS = ( + "extrq_imm_basic", + "extrq_imm_zero_len", + "extrq_imm_high_bit", + "extrq_imm_mid", + "extrq_imm_bits76", + "extrq_reg_basic", + "extrq_reg_self", + "extrq_reg_xmm4_xmm5", + "insertq_imm_basic", + "insertq_imm_zero_len", + "insertq_imm_high_bit", + "insertq_imm_self", + "insertq_reg_basic", + "insertq_reg_self", + "insertq_reg_xmm4_xmm5", + "movntsd_aligned", + "movntsd_disp8", + "movntsd_unaligned", + "movntss_aligned", + "movntss_disp12", + "movntss_unaligned", + "pipeline", +) + +OP_EXPORTS = tuple(f"op_{name}" for name in DIFF_EXPORTS) +REF_EXPORTS = tuple(f"ref_{name}" for name in DIFF_EXPORTS) +TRANSLATED_EXPORTS = OP_EXPORTS + ("op_discarded_read", "op_sse4a_discarded_read") + +ALTERED_EXPORTS = ( + "op_extrq_imm_basic", + "op_extrq_imm_zero_len", + "op_insertq_imm_basic", + "op_insertq_imm_zero_len", + "op_movntsd_disp8", + "op_movntss_disp12", +) + + +# --- Independent Python AMD64 APM reference model --- + +def u64(buf): + return struct.unpack("> offset) & mask + + +def apm_insertq(dst, src, len_imm, idx_imm): + """AMD64 APM Vol. 4 INSERTQ bit-field insertion.""" + width = (len_imm & 0x3F) or 64 + offset = idx_imm & 0x3F + assert offset + width <= 64, (width, offset) + mask = (1 << width) - 1 + return ((dst & ~(mask << offset)) | ((src & mask) << offset)) & MASK64 + + +def reference(export_name, a, b, altered=False): + """Expected 32-byte output region for an op_* or ref_* export.""" + stem = export_name[3:] if export_name.startswith(("op_", "ref_")) else export_name + out = bytearray(FILL) + + if stem == "extrq_imm_basic": + out[0:8] = pk_q(apm_extrq(u64(a[0:8]), 12, 24 if altered else 20)) + elif stem == "extrq_imm_zero_len": + out[0:8] = pk_q(apm_extrq(u64(a[0:8]), 63 if altered else 0, 0)) + elif stem == "extrq_imm_high_bit": + out[0:8] = pk_q(apm_extrq(u64(a[0:8]), 1, 63)) + elif stem == "extrq_imm_mid": + out[0:8] = pk_q(apm_extrq(u64(a[0:8]), 16, 48)) + elif stem == "extrq_imm_bits76": + out[0:8] = pk_q(apm_extrq(u64(a[0:8]), 0x48, 0x05)) + elif stem == "extrq_reg_basic": + ctrl = u64(b[0:8]) + out[0:8] = pk_q(apm_extrq(u64(a[0:8]), ctrl & 0xFF, (ctrl >> 8) & 0xFF)) + elif stem == "extrq_reg_self": + val = u64(a[0:8]) + out[0:8] = pk_q(apm_extrq(val, val & 0xFF, (val >> 8) & 0xFF)) + elif stem == "extrq_reg_xmm4_xmm5": + ctrl = u64(b[1:9]) + out[0:8] = pk_q(apm_extrq(u64(a[16:24]), ctrl & 0xFF, (ctrl >> 8) & 0xFF)) + elif stem == "insertq_imm_basic": + out[0:8] = pk_q(apm_insertq(u64(a[0:8]), u64(b[0:8]), 16, 20 if altered else 16)) + elif stem == "insertq_imm_zero_len": + out[0:8] = pk_q(apm_insertq(u64(a[0:8]), u64(b[0:8]), 63 if altered else 0, 0)) + elif stem == "insertq_imm_high_bit": + out[0:8] = pk_q(apm_insertq(u64(a[0:8]), u64(b[0:8]), 1, 63)) + elif stem == "insertq_imm_self": + val = u64(a[0:8]) + out[0:8] = pk_q(apm_insertq(val, val, 12, 36)) + elif stem == "insertq_reg_basic": + ctrl = u64(b[8:16]) + out[0:8] = pk_q(apm_insertq(u64(a[0:8]), u64(b[0:8]), ctrl & 0xFF, (ctrl >> 8) & 0xFF)) + elif stem == "insertq_reg_self": + val = u64(a[0:8]) + ctrl = u64(a[8:16]) + out[0:8] = pk_q(apm_insertq(val, val, ctrl & 0xFF, (ctrl >> 8) & 0xFF)) + elif stem == "insertq_reg_xmm4_xmm5": + ctrl = u64(b[9:17]) + out[0:8] = pk_q(apm_insertq(u64(a[16:24]), u64(b[1:9]), ctrl & 0xFF, (ctrl >> 8) & 0xFF)) + elif stem == "movntsd_aligned": + out[0:8] = a[0:8] + elif stem == "movntsd_disp8": + if altered: + out[16:24] = b[0:8] + else: + out[8:16] = b[0:8] + elif stem == "movntsd_unaligned": + out[1:9] = a[3:11] + elif stem == "movntss_aligned": + out[0:4] = a[0:4] + elif stem == "movntss_disp12": + if altered: + out[16:20] = b[0:4] + else: + out[12:16] = b[0:4] + elif stem == "movntss_unaligned": + out[3:7] = a[5:9] + elif stem == "pipeline": + xmm0 = apm_extrq(u64(a[0:8]), 16, 8) + xmm2 = apm_insertq(u64(a[16:24]), xmm0, 16, 24) + ctrl_ins = u64(b[8:16]) + xmm2 = apm_insertq(xmm2, u64(b[0:8]), ctrl_ins & 0xFF, (ctrl_ins >> 8) & 0xFF) + ctrl_ext = u64(b[0:8]) + xmm3 = apm_extrq(u64(b[16:24]), ctrl_ext & 0xFF, (ctrl_ext >> 8) & 0xFF) + out[0:8] = pk_q(xmm2) + out[8:16] = pk_q(xmm3) + out[16:20] = pk_d(xmm0) + out[21:25] = pk_d(xmm2) + else: + raise ValueError(f"unknown export {export_name}") + return bytes(out) + + +# --- Test vector generators (strictly defined offset + width <= 64 for reg forms) --- + +DEFINED_FIELDS = ( + (0, 0), # width=64, offset=0 + (0x40, 0), # bits[5:0]==0 -> width=64, bits[7:6] non-zero ignored + (1, 0), + (1, 63), + (8, 56), + (16, 0), + (16, 16), + (16, 48), + (32, 0), + (32, 32), + (63, 1), + (5, 11), + (0xC5, 0x8B), # bits[7:6] & [15:14] ignored -> width=5, offset=11 +) + +VALUES64 = ( + 0x0123456789ABCDEF, + 0xFEDCBA9876543210, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x8000000000000001, + 0x5555AAAA5555AAAA, + 0xAAAA5555AAAA5555, + 0x1122334455667788, +) + + +def make_ctrl(width_byte, offset_byte, garbage_hi): + return ((garbage_hi & 0xFFFFFFFFFFFF) << 16) | ((offset_byte & 0xFF) << 8) | (width_byte & 0xFF) + + +def pairs_for(export_name): + rng = random.Random(0x55E4A) + stem = export_name[3:] + + if stem == "extrq_reg_self": + pairs = [] + for idx, (w, o) in enumerate(DEFINED_FIELDS): + for hi in (0, 0x123456789ABC, 0xFFFFFFFFFFFF): + val = make_ctrl(w, o, hi ^ (VALUES64[idx % len(VALUES64)] >> 16)) + pairs.append((pk_q(val) + os_pad(24), b"\xAA" * 32)) + return pairs + + if stem == "insertq_reg_self": + pairs = [] + for idx, (w, o) in enumerate(DEFINED_FIELDS): + val = VALUES64[idx % len(VALUES64)] + ctrl = make_ctrl(w, o, 0xA5A55A5A1234 ^ idx) + pairs.append((pk_q(val) + pk_q(ctrl) + os_pad(16), b"\x55" * 32)) + return pairs + + if stem == "extrq_reg_basic": + pairs = [] + for w, o in DEFINED_FIELDS: + for a_val in VALUES64[:4]: + ctrl = make_ctrl(w, o, rng.getrandbits(48)) + pairs.append((pk_q(a_val) + os_pad(24), pk_q(ctrl) + os_pad(24))) + return pairs + + if stem == "extrq_reg_xmm4_xmm5": + pairs = [] + for w, o in DEFINED_FIELDS: + for a_val in VALUES64[:4]: + ctrl = make_ctrl(w, o, rng.getrandbits(48)) + a = os_pad(16) + pk_q(a_val) + os_pad(8) + b = b"\xCC" + pk_q(ctrl) + os_pad(23) + pairs.append((a, b)) + return pairs + + if stem == "insertq_reg_basic": + pairs = [] + for w, o in DEFINED_FIELDS: + for a_val, b_val in zip(VALUES64, reversed(VALUES64)): + ctrl = make_ctrl(w, o, rng.getrandbits(48)) + a = pk_q(a_val) + os_pad(24) + b = pk_q(b_val) + pk_q(ctrl) + os_pad(16) + pairs.append((a, b)) + return pairs + + if stem == "insertq_reg_xmm4_xmm5": + pairs = [] + for w, o in DEFINED_FIELDS: + for a_val, b_val in zip(VALUES64[:4], reversed(VALUES64[:4])): + ctrl = make_ctrl(w, o, rng.getrandbits(48)) + a = os_pad(16) + pk_q(a_val) + os_pad(8) + b = b"\xDD" + pk_q(b_val) + pk_q(ctrl) + os_pad(15) + pairs.append((a, b)) + return pairs + + if stem == "pipeline": + pairs = [] + for i, (w1, o1) in enumerate(DEFINED_FIELDS): + w2, o2 = DEFINED_FIELDS[(i * 5 + 3) % len(DEFINED_FIELDS)] + a_lo = VALUES64[i % len(VALUES64)] + a_hi = VALUES64[(i + 3) % len(VALUES64)] + b_lo = make_ctrl(w1, o1, rng.getrandbits(48)) + b_hi = make_ctrl(w2, o2, rng.getrandbits(48)) + b_ext_src = VALUES64[(i + 5) % len(VALUES64)] + a = pk_q(a_lo) + os_pad(8) + pk_q(a_hi) + os_pad(8) + b = pk_q(b_lo) + pk_q(b_hi) + pk_q(b_ext_src) + os_pad(8) + pairs.append((a, b)) + return pairs + + # Immediate extrq/insertq and movntsd/movntss forms. + pairs = [ + (bytes(range(0x10, 0x30)), bytes(range(0x80, 0xA0))), + (b"\x00" * 32, b"\xFF" * 32), + (b"\xFF" * 32, b"\x00" * 32), + (pk_q(VALUES64[0]) * 4, pk_q(VALUES64[1]) * 4), + (pk_q(VALUES64[4]) * 4, pk_q(VALUES64[5]) * 4), + ] + for _ in range(12): + pairs.append((rng.randbytes(32), rng.randbytes(32))) + return pairs + + +def os_pad(n): + return bytes((0x37 + i * 17) & 0xFF for i in range(n)) + + +# --- Guarded buffer helpers --- + +def alloc_aligned_buffer(payload, align=16): + total = len(GUARD_PRE) + len(payload) + len(GUARD_POST) + align + buf = ctypes.create_string_buffer(total) + base_addr = ctypes.addressof(buf) + start_after_guard = base_addr + len(GUARD_PRE) + pad = (align - start_after_guard % align) % align + payload_off = len(GUARD_PRE) + pad + pre_off = payload_off - len(GUARD_PRE) + post_off = payload_off + len(payload) + buf[pre_off:payload_off] = GUARD_PRE + buf[payload_off:post_off] = payload + buf[post_off:post_off + len(GUARD_POST)] = GUARD_POST + return buf, base_addr + payload_off, pre_off, payload_off, post_off + + +def check_guards_and_read(buf, pre_off, payload_off, post_off, label): + raw = buf.raw + if raw[pre_off:payload_off] != GUARD_PRE or raw[post_off:post_off + len(GUARD_POST)] != GUARD_POST: + raise AssertionError(f"guard bytes corrupted around {label}") + return raw[payload_off:post_off] + + +def invoke(fn, a, b): + buf_a, ptr_a, a_pre, a_off, a_post = alloc_aligned_buffer(a) + buf_b, ptr_b, b_pre, b_off, b_post = alloc_aligned_buffer(b) + buf_out, ptr_out, o_pre, o_off, o_post = alloc_aligned_buffer(FILL) + fn(ptr_a, ptr_b, ptr_out) + check_guards_and_read(buf_a, a_pre, a_off, a_post, "input_a") + check_guards_and_read(buf_b, b_pre, b_off, b_post, "input_b") + return check_guards_and_read(buf_out, o_pre, o_off, o_post, "output") + + +def assert_equal_output(label, name, idx, got, want): + if got != want: + raise AssertionError( + f"{label} {name} case {idx}: got {got.hex()} != expected {want.hex()}" + ) + + +def bind_exports(dll_path, prefix="", names=OP_EXPORTS): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in names: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64] + fn.restype = None + funcs[name] = fn + return lib, funcs + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in TRANSLATED_EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +# --- Discarded-read fault ordering --- + +def check_discarded_read(native_path, lifted_path, native_sse4a): + payload = bytes(range(32)) + + # Universal op_discarded_read runs natively and lifted on both Intel and AMD. + for label, dll, prefix in (("native", native_path, ""), ("lifted", lifted_path, "lifted_")): + _, fns = bind_exports(dll, prefix, ("op_discarded_read",)) + fn = fns["op_discarded_read"] + source, ptr, _, _, _ = alloc_aligned_buffer(payload) + for readable in (True, False): + result, result_ptr, pre, off, post = alloc_aligned_buffer(FILL) + try: + fn(ptr, ptr if readable else 0, result_ptr) + except OSError as error: + assert not readable and "access violation reading" in str(error).lower(), (label, error) + else: + assert readable, f"{label} discarded a faulting read" + expected = payload[:16] + (payload[:16] if readable else FILL[16:]) + assert_equal_output(label, "op_discarded_read", readable, + check_guards_and_read(result, pre, off, post, label), expected) + + # SSE4a dead-read export always runs on lifted, and runs on native when host supports SSE4a. + targets = [("lifted", lifted_path, "lifted_")] + if native_sse4a: + targets.insert(0, ("native", native_path, "")) + for label, dll, prefix in targets: + _, fns = bind_exports(dll, prefix, ("op_sse4a_discarded_read",)) + fn = fns["op_sse4a_discarded_read"] + source, ptr, _, _, _ = alloc_aligned_buffer(payload) + for readable in (True, False): + result, result_ptr, pre, off, post = alloc_aligned_buffer(FILL) + try: + fn(ptr, ptr if readable else 0, result_ptr) + except OSError as error: + assert not readable and "access violation reading" in str(error).lower(), (label, error) + else: + assert readable, f"{label} discarded a faulting SSE4a read" + expected = payload[:8] + (payload[:4] if readable else FILL[8:12]) + FILL[12:] + assert_equal_output(label, "op_sse4a_discarded_read", readable, + check_guards_and_read(result, pre, off, post, label), expected) + + +# --- Differential verification & altered/mutation controls --- + +def check_differential(native_path, lifted_path, altered_path): + lifted_lib, lifted = bind_exports(lifted_path, "lifted_", OP_EXPORTS) + lifted_lib.host_has_sse4a.argtypes = [] + lifted_lib.host_has_sse4a.restype = ctypes.c_uint32 + native_sse4a = bool(lifted_lib.host_has_sse4a()) + + check_discarded_read(native_path, lifted_path, native_sse4a) + + _, ref_fns = bind_exports(native_path, "", REF_EXPORTS) + _, native_ops = bind_exports(native_path, "", OP_EXPORTS) if native_sse4a else (None, None) + _, altered = bind_exports(altered_path, "lifted_", ALTERED_EXPORTS) + + total = 0 + for op_name, ref_name in zip(OP_EXPORTS, REF_EXPORTS): + for idx, (a, b) in enumerate(pairs_for(op_name)): + want = reference(op_name, a, b) + got_l = invoke(lifted[op_name], a, b) + got_r = invoke(ref_fns[ref_name], a, b) + assert_equal_output("lifted", op_name, idx, got_l, want) + assert_equal_output("masm_ref", ref_name, idx, got_r, want) + if native_ops is not None: + got_n = invoke(native_ops[op_name], a, b) + assert_equal_output("native_sse4a", op_name, idx, got_n, want) + total += 1 + + changed = {} + for name in ALTERED_EXPORTS: + diffs = 0 + for idx, (a, b) in enumerate(pairs_for(name)): + want_alt = reference(name, a, b, altered=True) + want_orig = reference(name, a, b) + got_alt = invoke(altered[name], a, b) + assert_equal_output("altered", name, idx, got_alt, want_alt) + if got_alt != want_orig: + diffs += 1 + if not diffs: + raise AssertionError(f"altered control {name} did not diverge from original") + changed[name] = diffs + + sample_a, sample_b = pairs_for("op_pipeline")[0] + expected = reference("op_pipeline", sample_a, sample_b) + mutated = bytearray(expected) + mutated[5] ^= 0x01 + try: + assert_equal_output("mutation", "op_pipeline", 0, bytes(mutated), expected) + except AssertionError: + pass + else: + raise AssertionError("mutated output was not caught by comparator") + + mode_note = "native SSE4a + MASM ref + lifted + APM" if native_sse4a else "MASM ref + lifted + APM (host lacks CPUID SSE4a)" + print(f"{total} cases across {len(OP_EXPORTS)} exports matched bit-for-bit ({mode_note}); " + f"ALTER_IMM diverged on all {len(changed)} exports (min diffs {min(changed.values())}); " + f"discarded-read and output-mutation controls passed") + + +# --- Alternate-encoding acceptance & strict rejection controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_alt_encodings_and_rejections(original_path): + ld_xmm0 = Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + ld_xmm1 = Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM1, MemoryOperand(R.RDX)) + ld_xmm4 = Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM4, MemoryOperand(R.RCX)) + ld_xmm5 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM5, MemoryOperand(R.RDX, displ=3, displ_size=1)) + st_xmm0 = Instruction.create_mem_reg(Code.MOVAPS_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + ret_ins = Instruction.create(Code.RETNQ) + + alt_accept = [ + ("extrq_imm_xmm4_64", (ld_xmm4, Instruction.create_reg_u32_u32( + Code.EXTRQ_XMM_IMM8_IMM8, R.XMM4, 0x40, 0), + Instruction.create_mem_reg(Code.MOVNTSD_M64_XMM, MemoryOperand(R.R8), R.XMM4), ret_ins)), + ("extrq_reg_xmm5_xmm4", (ld_xmm4, ld_xmm5, Instruction.create_reg_reg( + Code.EXTRQ_XMM_XMM, R.XMM5, R.XMM4), + Instruction.create_mem_reg(Code.MOVNTSS_M32_XMM, MemoryOperand(R.R8, displ=7, displ_size=1), R.XMM5), + ret_ins)), + ("insertq_imm_xmm4_xmm5", (ld_xmm4, ld_xmm5, Instruction.create_reg_reg_u32_u32( + Code.INSERTQ_XMM_XMM_IMM8_IMM8, R.XMM4, R.XMM5, 8, 56), + Instruction.create_mem_reg(Code.MOVNTSD_M64_XMM, MemoryOperand(R.R8, displ=-3, displ_size=1), R.XMM4), + ret_ins)), + ("insertq_reg_xmm4_xmm5", (ld_xmm4, ld_xmm5, Instruction.create_reg_reg( + Code.INSERTQ_XMM_XMM, R.XMM4, R.XMM5), + Instruction.create_mem_reg(Code.MOVNTSS_M32_XMM, MemoryOperand(R.R8), R.XMM4), ret_ins)), + ("movdqu_r8_source", (Instruction.create_reg_mem( + Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.R8, displ=1, displ_size=1)), + Instruction.create_mem_reg(Code.MOVNTSD_M64_XMM, MemoryOperand(R.R8, displ=9, displ_size=1), R.XMM0), + ret_ins)), + ("movaps_alt_reg_reg", (ld_xmm0, Instruction.create_reg_reg( + Code.MOVAPS_XMMM128_XMM, R.XMM2, R.XMM0), + Instruction.create_mem_reg(Code.MOVNTSS_M32_XMM, MemoryOperand(R.R8), R.XMM2), ret_ins)), + ] + alt_expected = { + "extrq_imm_xmm4_64": "xmm4.q[0] = op_extrq_imm(xmm4.q[0], 0x40u, 0x0u);", + "extrq_reg_xmm5_xmm4": "xmm5.q[0] = op_extrq_reg(xmm5.q[0], xmm4.q[0]);", + "insertq_imm_xmm4_xmm5": "xmm4.q[0] = op_insertq_imm(xmm4.q[0], xmm5.q[0], 0x8u, 0x38u);", + "insertq_reg_xmm4_xmm5": "xmm4.q[0] = op_insertq_reg(xmm4.q[0], xmm5);", + "movdqu_r8_source": "load_always((r8 + 0x1ull))", + "movaps_alt_reg_reg": "xmm2 = xmm0;", + } + for label, seq in alt_accept: + raw = encode_seq(*seq) + decoded = list(Decoder(64, raw, ip=0x1000)) + assert len(decoded) == len(seq) and not any(ins.is_invalid for ins in decoded), label + src, count = lift_code(label, 0x1000, raw) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if alt_expected[label] not in src: + raise AssertionError( + f"alternate encoding {label} lowered without expected {alt_expected[label]!r}") + + # 1) Immediate offset + width > 64 rejections. + oob_cases = [ + ("extrq_imm_oob_32_33", (ld_xmm0, Instruction.create_reg_u32_u32( + Code.EXTRQ_XMM_IMM8_IMM8, R.XMM0, 32, 33), ret_ins), "undefined SSE4a bitfield"), + ("extrq_imm_oob_0_1", (ld_xmm0, Instruction.create_reg_u32_u32( + Code.EXTRQ_XMM_IMM8_IMM8, R.XMM0, 0, 1), ret_ins), "undefined SSE4a bitfield"), + ("extrq_imm_oob_40_1", (ld_xmm0, Instruction.create_reg_u32_u32( + Code.EXTRQ_XMM_IMM8_IMM8, R.XMM0, 0x40, 1), ret_ins), "undefined SSE4a bitfield"), + ("insertq_imm_oob_48_48", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_u32_u32( + Code.INSERTQ_XMM_XMM_IMM8_IMM8, R.XMM0, R.XMM1, 48, 48), ret_ins), "undefined SSE4a bitfield"), + ("insertq_imm_oob_0_1", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_u32_u32( + Code.INSERTQ_XMM_XMM_IMM8_IMM8, R.XMM0, R.XMM1, 0, 1), ret_ins), "undefined SSE4a bitfield"), + ] + + # 2) Non-legacy VEX and EVEX encodings. + nonlegacy_cases = [ + ("vmovaps_vex", (Instruction.create_reg_mem( + Code.VEX_VMOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret_ins), "non-legacy encoding"), + ("vmovdqu_vex", (Instruction.create_reg_mem( + Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret_ins), "non-legacy encoding"), + ("vmovntps_vex", (ld_xmm0, Instruction.create_mem_reg( + Code.VEX_VMOVNTPS_M128_XMM, MemoryOperand(R.R8), R.XMM0), ret_ins), "non-legacy encoding"), + ("vmovaps_evex", (Instruction.create_reg_mem( + Code.EVEX_VMOVAPS_XMM_K1Z_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret_ins), "non-legacy encoding"), + ("vmovntps_evex", (ld_xmm0, Instruction.create_mem_reg( + Code.EVEX_VMOVNTPS_M128_XMM, MemoryOperand(R.R8), R.XMM0), ret_ins), "non-legacy encoding"), + ] + + # 3) Unsupported instructions. + unsupported_insns = [ + ("movntps", (ld_xmm0, Instruction.create_mem_reg(Code.MOVNTPS_M128_XMM, MemoryOperand(R.R8), R.XMM0), ret_ins)), + ("movntpd", (ld_xmm0, Instruction.create_mem_reg(Code.MOVNTPD_M128_XMM, MemoryOperand(R.R8), R.XMM0), ret_ins)), + ("movss", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.MOVSS_XMM_XMMM32, R.XMM0, R.XMM1), ret_ins)), + ("movsd", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.MOVSD_XMM_XMMM64, R.XMM0, R.XMM1), ret_ins)), + ("addps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.ADDPS_XMM_XMMM128, R.XMM0, R.XMM1), ret_ins)), + ("pextrq", (ld_xmm0, Instruction.create_reg_reg_u32(Code.PEXTRQ_RM64_XMM_IMM8, R.RAX, R.XMM0, 0), ret_ins)), + ("mov_gpr", (Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RBX, R.RCX), ret_ins)), + ] + + # 4) Nonvolatile registers, unowned stores, undefined reads, alignment, prefixes, stream checks. + seg_load = Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + seg_load.segment_prefix = R.GS + other_cases = [ + ("nonvolatile_xmm6_extrq_imm", (Instruction.create_reg_mem( + Code.MOVAPS_XMM_XMMM128, R.XMM6, MemoryOperand(R.RCX)), ret_ins), "nonvolatile vector register"), + ("nonvolatile_xmm8_extrq_reg", (ld_xmm0, Instruction.create_reg_reg( + Code.EXTRQ_XMM_XMM, R.XMM0, R.XMM8), ret_ins), "nonvolatile vector register"), + ("nonvolatile_xmm7_insertq_imm", (ld_xmm0, Instruction.create_reg_reg_u32_u32( + Code.INSERTQ_XMM_XMM_IMM8_IMM8, R.XMM0, R.XMM7, 8, 8), ret_ins), "nonvolatile vector register"), + ("nonvolatile_xmm10_insertq_reg", (ld_xmm0, Instruction.create_reg_reg( + Code.INSERTQ_XMM_XMM, R.XMM0, R.XMM10), ret_ins), "nonvolatile vector register"), + ("nonvolatile_xmm9_movntsd", (Instruction.create_mem_reg( + Code.MOVNTSD_M64_XMM, MemoryOperand(R.R8), R.XMM9), ret_ins), "nonvolatile vector register"), + ("nonvolatile_xmm15_movntss", (Instruction.create_mem_reg( + Code.MOVNTSS_M32_XMM, MemoryOperand(R.R8), R.XMM15), ret_ins), "nonvolatile vector register"), + ("undefined_extrq_imm", (Instruction.create_reg_u32_u32( + Code.EXTRQ_XMM_IMM8_IMM8, R.XMM0, 8, 8), ret_ins), "undefined vector register xmm0"), + ("undefined_extrq_reg_src", (ld_xmm0, Instruction.create_reg_reg( + Code.EXTRQ_XMM_XMM, R.XMM0, R.XMM3), ret_ins), "undefined vector register xmm3"), + ("undefined_insertq_imm_dst", (ld_xmm1, Instruction.create_reg_reg_u32_u32( + Code.INSERTQ_XMM_XMM_IMM8_IMM8, R.XMM0, R.XMM1, 8, 8), ret_ins), "undefined vector register xmm0"), + ("undefined_insertq_reg_src", (ld_xmm0, Instruction.create_reg_reg( + Code.INSERTQ_XMM_XMM, R.XMM0, R.XMM2), ret_ins), "undefined vector register xmm2"), + ("undefined_movntsd_src", (Instruction.create_mem_reg( + Code.MOVNTSD_M64_XMM, MemoryOperand(R.R8), R.XMM4), ret_ins), "undefined vector register xmm4"), + ("undefined_movntss_src", (Instruction.create_mem_reg( + Code.MOVNTSS_M32_XMM, MemoryOperand(R.R8), R.XMM5), ret_ins), "undefined vector register xmm5"), + ("non_r8_store_movntsd_rcx", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSD_M64_XMM, MemoryOperand(R.RCX), R.XMM0), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_movntsd_rdx", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSD_M64_XMM, MemoryOperand(R.RDX, displ=8, displ_size=1), R.XMM0), ret_ins), + "non-r8 store memory operand"), + ("non_r8_store_movntss_rcx", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSS_M32_XMM, MemoryOperand(R.RCX), R.XMM0), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_movntss_rdx", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSS_M32_XMM, MemoryOperand(R.RDX, displ=4, displ_size=1), R.XMM0), ret_ins), + "non-r8 store memory operand"), + ("nonvolatile_gpr_rbx", (Instruction.create_reg_mem( + Code.MOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RBX)), ret_ins), "nonvolatile GPR base"), + ("nonvolatile_gpr_r12_movntsd", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSD_M64_XMM, MemoryOperand(R.R12), R.XMM0), ret_ins), "nonvolatile GPR base"), + ("nonvolatile_gpr_rsi_movntss", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSS_M32_XMM, MemoryOperand(R.RSI), R.XMM0), ret_ins), "nonvolatile GPR base"), + ("non_arg_base_rax", (Instruction.create_reg_mem( + Code.MOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RAX)), ret_ins), "unsupported memory base"), + ("non_arg_base_r9_movntsd", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSD_M64_XMM, MemoryOperand(R.R9), R.XMM0), ret_ins), "unsupported memory base"), + ("rip_rel_movntsd", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSD_M64_XMM, MemoryOperand(R.RIP, displ=0x1010, displ_size=1), R.XMM0), ret_ins), + "unsupported memory operand"), + ("rsp_movntss", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSS_M32_XMM, MemoryOperand(R.RSP), R.XMM0), ret_ins), "unsupported memory operand"), + ("addr32_movntss", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSS_M32_XMM, MemoryOperand(R.R8D), R.XMM0), ret_ins), "unsupported memory operand"), + ("indexed_movntsd", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVNTSD_M64_XMM, MemoryOperand(R.R8, R.RCX, 4), R.XMM0), ret_ins), + "unsupported memory operand"), + ("unaligned_movaps_m128", (Instruction.create_reg_mem( + Code.MOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX, displ=1, displ_size=1)), ret_ins), + "unaligned 16-byte memory operand"), + ("segment_prefix", (seg_load, ret_ins), "unsupported instruction prefix"), + ("missing_ret", (ld_xmm0, st_xmm0), "missing terminal ret"), + ("after_ret", (ret_ins, ld_xmm0), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("extrq_slash1", bytes.fromhex("660f78c81010") + encode_seq(ret_ins), "invalid instruction"), + ("movntsd_reg_invalid", bytes.fromhex("f20f2bc0") + encode_seq(ret_ins), "invalid instruction"), + ("movntss_reg_invalid", bytes.fromhex("f30f2bc0") + encode_seq(ret_ins), "invalid instruction"), + ("lock_cmpxchg", bytes.fromhex("f00fb109") + encode_seq(ret_ins), "unsupported instruction prefix"), + ("rep_movsb", bytes.fromhex("f3a4") + encode_seq(ret_ins), "unsupported instruction prefix"), + ("invalid_ud_bytes", bytes.fromhex("fffe") + encode_seq(ret_ins), "invalid instruction"), + ("truncated_insn", encode_seq(ld_xmm0)[:-1], "invalid instruction"), + ("empty_stream", b"", "truncated instruction stream"), + ] + + all_unit = ( + oob_cases + + nonlegacy_cases + + [(lbl, seq, "unsupported instruction") for lbl, seq in unsupported_insns] + + other_cases + ) + + for label, seq, expected_reason in all_unit: + raw = encode_seq(*seq) + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if expected_reason not in str(exc): + raise AssertionError(f"{label}: expected {expected_reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator unexpectedly accepted rejected control") + + for label, raw, expected_reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if expected_reason not in str(exc): + raise AssertionError(f"{label}: expected {expected_reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator unexpectedly accepted rejected control") + + # End-to-end PE patching controls on a copy of the built native DLL. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_pipeline") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) + if struct.unpack_from(" max_len: + raise AssertionError(f"{label}: patch ({len(patch)} bytes) exceeds op_pipeline ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into(" 64 + - extrq (register form, 66 0F 79 /r): extract bit field from xmm1[63:0] using + length=xmm2[5:0] (0 -> 64) and index=xmm2[13:8] + - insertq (immediate form, F2 0F 78 /r ib ib): insert bits [width-1:0] of + xmm2[63:0] into xmm1[63:0] at offset; rejects static offset + width > 64 + - insertq (register form, F2 0F 79 /r): insert bits [width-1:0] of xmm2[63:0] + into xmm1[63:0] using length=xmm2[69:64] (0 -> 64) and index=xmm2[77:72] + - movntsd (F2 0F 2B /r): unaligned non-temporal 64-bit store to [r8 + disp] + - movntss (F3 0F 2B /r): unaligned non-temporal 32-bit store to [r8 + disp] + +Bits 127:64 of an extrq/insertq destination are architecturally undefined per +the AMD64 APM; this lifter leaves dst.q[1] unchanged and tests only observe the +defined low 64 bits. + +Transport/ABI glue: movaps, movdqa (16-byte aligned 128-bit load/store/reg +copy), movdqu (unaligned 128-bit load/store/reg copy) and terminal ret. All +memory stores must target an r8-rooted flat address; loads may read from rcx, +rdx or r8. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import Code, Decoder, EncodingKind, OpKind, Register as R, RegisterExt + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 16)} + | {getattr(R, f"YMM{i}") for i in range(6, 16)} + | {getattr(R, f"ZMM{i}") for i in range(6, 32)} +) +NONVOLATILE_GPR = { + R.EBX, R.RBX, R.EBP, R.RBP, R.ESI, R.RSI, R.EDI, R.RDI, R.ESP, R.RSP, + R.R12D, R.R12, R.R13D, R.R13, R.R14D, R.R14, R.R15D, R.R15, +} + +LOAD_ALIGNED_VEC_CODES = {Code.MOVAPS_XMM_XMMM128, Code.MOVDQA_XMM_XMMM128} +STORE_ALIGNED_VEC_CODES = {Code.MOVAPS_XMMM128_XMM, Code.MOVDQA_XMMM128_XMM} + +ALLOWED_CODES = { + Code.RETNQ, + Code.EXTRQ_XMM_IMM8_IMM8, + Code.EXTRQ_XMM_XMM, + Code.INSERTQ_XMM_XMM_IMM8_IMM8, + Code.INSERTQ_XMM_XMM, + Code.MOVNTSD_M64_XMM, + Code.MOVNTSS_M32_XMM, + Code.MOVAPS_XMM_XMMM128, + Code.MOVAPS_XMMM128_XMM, + Code.MOVDQA_XMM_XMMM128, + Code.MOVDQA_XMMM128_XMM, + Code.MOVDQU_XMM_XMMM128, + Code.MOVDQU_XMMM128_XMM, +} + +PRELUDE = """#include +#include +#include + +extern "C" __declspec(dllexport) std::uint32_t host_has_sse4a() { + int info[4]{}; + __cpuid(info, 0x80000000); + if (static_cast(info[0]) < 0x80000001u) return 0u; + __cpuid(info, 0x80000001); + return (static_cast(info[2]) & (1u << 6)) != 0u ? 1u : 0u; +} + +using word = std::uint64_t; + +struct Vec128 { + std::uint64_t q[2]; +}; + +// Guest reads can fault even when the translated result is dead. Keep surrounding guest +// writes on their original side of the read when the compiler inlines these helpers. +static inline Vec128 load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* src = reinterpret_cast(address); + const std::uint64_t q0 = src[0]; + const std::uint64_t q1 = src[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1}}; +} + +static inline void store32(word address, std::uint32_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + *reinterpret_cast(address) = val; + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store64(word address, std::uint64_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + *reinterpret_cast(address) = val; + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store128(word address, const Vec128& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + auto* dst = reinterpret_cast(address); + dst[0] = v.q[0]; + dst[1] = v.q[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline std::uint64_t sse4a_extract(std::uint64_t dst, unsigned width, unsigned offset) { + if (offset + width > 64u) { + return 0ull; + } + const std::uint64_t mask = (width == 64u) ? ~0ull : ((1ull << width) - 1ull); + return (dst >> offset) & mask; +} + +static inline std::uint64_t sse4a_insert( + std::uint64_t dst, std::uint64_t src, unsigned width, unsigned offset) { + if (offset + width > 64u) { + return 0ull; + } + const std::uint64_t mask = (width == 64u) ? ~0ull : ((1ull << width) - 1ull); + const std::uint64_t field_mask = mask << offset; + return (dst & ~field_mask) | ((src & mask) << offset); +} + +static inline std::uint64_t op_extrq_imm( + std::uint64_t dst, std::uint8_t len_imm, std::uint8_t idx_imm) { + const unsigned raw_len = static_cast(len_imm & 0x3fu); + const unsigned width = raw_len == 0u ? 64u : raw_len; + const unsigned offset = static_cast(idx_imm & 0x3fu); + return sse4a_extract(dst, width, offset); +} + +static inline std::uint64_t op_extrq_reg(std::uint64_t dst, std::uint64_t ctrl) { + const unsigned raw_len = static_cast(ctrl & 0x3full); + const unsigned width = raw_len == 0u ? 64u : raw_len; + const unsigned offset = static_cast((ctrl >> 8) & 0x3full); + return sse4a_extract(dst, width, offset); +} + +static inline std::uint64_t op_insertq_imm( + std::uint64_t dst, std::uint64_t src, std::uint8_t len_imm, std::uint8_t idx_imm) { + const unsigned raw_len = static_cast(len_imm & 0x3fu); + const unsigned width = raw_len == 0u ? 64u : raw_len; + const unsigned offset = static_cast(idx_imm & 0x3fu); + return sse4a_insert(dst, src, width, offset); +} + +static inline std::uint64_t op_insertq_reg(std::uint64_t dst, const Vec128& src) { + const std::uint64_t ctrl = src.q[1]; + const unsigned raw_len = static_cast(ctrl & 0x3full); + const unsigned width = raw_len == 0u ? 64u : raw_len; + const unsigned offset = static_cast((ctrl >> 8) & 0x3full); + return sse4a_insert(dst, src.q[0], width, offset); +} +""" + + +def vec_index(register, ins): + """Map XMM0..XMM5 to an index, rejecting nonvolatile and unsupported registers.""" + if register in VOLATILE_XMM: + return VOLATILE_XMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, alignment=1, write=False): + """Lower a flat [base + disp] pointer operand rooted in an argument GPR64.""" + base = ins.memory_base + if (ins.is_ip_rel_memory_operand or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE or not RegisterExt.is_gpr64(base)): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in memory operand at RVA {ins.ip:#x}: {ins}") + if base not in ARGUMENTS: + raise ValueError(f"unsupported memory base {base} at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + disp = ins.memory_displacement & ((1 << 64) - 1) + if disp % alignment: + raise ValueError(f"unaligned {alignment}-byte memory operand at RVA {ins.ip:#x}: {ins}") + name = ARGUMENTS[base] + return f"({name} + {disp:#x}ull)" if disp else name + + +def validate_sse4a_imm(len_imm, idx_imm, ins): + """Validate immediate SSE4a bitfield bounds (offset + width <= 64).""" + width = (len_imm & 0x3F) or 64 + offset = idx_imm & 0x3F + if offset + width > 64: + raise ValueError( + f"undefined SSE4a bitfield (width {width} + offset {offset} > 64) " + f"at RVA {ins.ip:#x}: {ins}" + ) + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line legacy SSE4a leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used = set() + defined = set() + statements = [] + returned = False + + def read_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + if idx not in defined: + raise ValueError(f"undefined vector register xmm{idx} at RVA {ins.ip:#x}: {ins}") + used.add(idx) + return f"xmm{idx}" + + def write_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + used.add(idx) + return idx, f"xmm{idx}" + + def vec_src128(op_index, ins, *, alignment): + if ins.op_kind(op_index) == OpKind.MEMORY: + return f"load_always({flat_address(ins, alignment=alignment)})" + return read_vec(op_index, ins) + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if (ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix + or ins.has_segment_prefix or ins.has_xacquire_prefix or ins.has_xrelease_prefix): + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + if ins.op_code().encoding != EncodingKind.LEGACY: + raise ValueError(f"non-legacy encoding at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + elif ins.code == Code.EXTRQ_XMM_IMM8_IMM8: + len_imm = ins.immediate8 & 0xFF + idx_imm = ins.immediate8_2nd & 0xFF + validate_sse4a_imm(len_imm, idx_imm, ins) + dst = read_vec(0, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append( + f"{dst_name}.q[0] = op_extrq_imm({dst}.q[0], {len_imm:#x}u, {idx_imm:#x}u);" + ) + defined.add(dst_idx) + elif ins.code == Code.EXTRQ_XMM_XMM: + dst = read_vec(0, ins) + src = read_vec(1, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name}.q[0] = op_extrq_reg({dst}.q[0], {src}.q[0]);") + defined.add(dst_idx) + elif ins.code == Code.INSERTQ_XMM_XMM_IMM8_IMM8: + len_imm = ins.immediate8 & 0xFF + idx_imm = ins.immediate8_2nd & 0xFF + validate_sse4a_imm(len_imm, idx_imm, ins) + dst = read_vec(0, ins) + src = read_vec(1, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append( + f"{dst_name}.q[0] = op_insertq_imm({dst}.q[0], {src}.q[0], {len_imm:#x}u, {idx_imm:#x}u);" + ) + defined.add(dst_idx) + elif ins.code == Code.INSERTQ_XMM_XMM: + dst = read_vec(0, ins) + src = read_vec(1, ins) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name}.q[0] = op_insertq_reg({dst}.q[0], {src});") + defined.add(dst_idx) + elif ins.code == Code.MOVNTSD_M64_XMM: + if ins.op0_kind != OpKind.MEMORY: + raise ValueError(f"expected memory destination at RVA {ins.ip:#x}: {ins}") + src = read_vec(1, ins) + statements.append(f"store64({flat_address(ins, write=True)}, {src}.q[0]);") + elif ins.code == Code.MOVNTSS_M32_XMM: + if ins.op0_kind != OpKind.MEMORY: + raise ValueError(f"expected memory destination at RVA {ins.ip:#x}: {ins}") + src = read_vec(1, ins) + statements.append( + f"store32({flat_address(ins, write=True)}, static_cast({src}.q[0]));" + ) + elif ins.code in (*LOAD_ALIGNED_VEC_CODES, Code.MOVDQU_XMM_XMMM128): + alignment = 16 if ins.code in LOAD_ALIGNED_VEC_CODES else 1 + src = vec_src128(1, ins, alignment=alignment) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = {src};") + defined.add(dst_idx) + elif ins.code in (*STORE_ALIGNED_VEC_CODES, Code.MOVDQU_XMMM128_XMM): + alignment = 16 if ins.code in STORE_ALIGNED_VEC_CODES else 1 + src = read_vec(1, ins) + if ins.op0_kind == OpKind.MEMORY: + statements.append( + f"store128({flat_address(ins, alignment=alignment, write=True)}, {src});" + ) + else: + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = {src};") + defined.add(dst_idx) + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec128 xmm{idx}{{}};" for idx in sorted(used)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, args.exports.split(",")) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") From 76de549a59df322cb7c6205993155b97fb780864 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:33:59 +0100 Subject: [PATCH 042/775] gfx2hlsl: lower per-lane bit operations (bfe_i32, bcnt, ffbl, ffbh, bfrev) --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 10 + docs/experiments.md | 6 + tests/startup_gfx2hlsl_bit_alu_check.py | 398 ++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 12 + 5 files changed, 428 insertions(+) create mode 100644 tests/startup_gfx2hlsl_bit_alu_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b73d82490..c1e3f13b0 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -52,6 +52,7 @@ jobs: python3 -B tests/startup_image_load_mip_check.py --llvm-mc llvm-mc-15 python3 -B tests/startup_image_2d_array_check.py binary llvm-mc-15 python3 -B tests/startup_flat_param_check.py binary llvm-mc-15 + python3 -B tests/startup_gfx2hlsl_bit_alu_check.py binary llvm-mc-15 python3 -B tests/startup_inline_sampler_check.py binary llvm-mc-15 LLVM_LIB=libLLVM-15.so.1 LLVM_MC=llvm-mc-15 LLVM_OBJCOPY=llvm-objcopy-15 python3 -B tests/rdna2_tools_check.py python-linux: @@ -113,6 +114,7 @@ jobs: python -B tests/startup_host_cpu_check.py python -B tests/startup_translator_check.py python -B tests/startup_flat_param_check.py + python -B tests/startup_gfx2hlsl_bit_alu_check.py python -B tests/startup_inline_sampler_check.py build-and-test: name: Build and test on Windows diff --git a/CMakeLists.txt b/CMakeLists.txt index 53b8344d2..391241f34 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1384,6 +1384,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_flat_param_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl per-lane bit operations: CPU evaluation of the translated text against an independent + # reference with mutation controls, then a desktop draw of the translated pairs (FXC 5_1 and DXC 6_0). + add_test(NAME startup_gfx2hlsl_bit_alu_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_bit_alu_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bit_alu_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_bit_alu_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_bit_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_xg_bc_tiling COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_xg_bc_tiling_check.py" "$") set_tests_properties(startup_xg_bc_tiling PROPERTIES TIMEOUT 30 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1") diff --git a/docs/experiments.md b/docs/experiments.md index 883ceea4d..35c7b263f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9478,6 +9478,12 @@ measurement on hardware or in a Windows run backs the descriptions. `v_interp_p1 `tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array, cube and multisample dimensions, an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) +## Startup translator: per-lane bit operations + +`tools/startup/gfx2hlsl.py` now lowers six gfx1013 per-lane bit operations that it used to refuse: `v_bfe_i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32`, `v_ffbh_i32` and `v_bfrev_b32`. They become single HLSL expressions, so no helper function is added to the output: `countbits(a) + b`, `firstbitlow(a)`, `reversebits(a)`, and, for the two high scans, `a == 0u ? 0xffffffffu : 31u - firstbithigh(a)` (the signed form scans `~a` for a negative value and reads 0xffffffff for 0 and -1). `v_bfe_i32` takes the offset from bits 4:0 of source 1 and the width from bits 4:0 of source 2, reads 0 for a width of 0, and sign-extends the field from its top bit; when offset plus width passes 32, the bits above bit 31 repeat bit 31, which is an arithmetic shift of the whole word. The formulas and edge cases are the ones `tools/pixel_aot.py` already draws on WARP. `v_bfe_i32` and `v_bcnt_u32_b32` exist only as VOP3 on gfx1013 (llvm-mc 19 rejects `_e32`); the other four assemble in both `_e32` and `_e64`. Source modifiers, `clamp`, output modifiers, `op_sel` and a wrong operand count are refused with `Unsupported`; the operand count is now checked for every integer operation in this table, where a missing operand used to raise `IndexError`. Not lowered here: the 64-bit carry forms, `v_bfm_b32`, the 24-bit multiplies and `v_alignbit_b32`. + +`tests/startup_gfx2hlsl_bit_alu_check.py` translates a source-built pixel stage that applies each operation to four lanes (the VOP1 operations alternate `_e32` and `_e64`) and evaluates the generated text with a small 32-bit HLSL evaluator against a reference written from the ISA description with bit loops, string reversal and integer arithmetic. The grid holds 17,459 inputs for `v_bfe_i32` (every offset and width 0 to 31 for 17 base words, plus offsets and widths above 31), 324 for `v_bcnt_u32_b32` and 81 for each scan. Each lowering also has a mutation that must read a wrong word: no sign extension, no addend, 0 instead of 0xffffffff for zero, no `31u -`, a negative value scanned unchanged, and no bit reversal. On `origin/main` the check fails with `Unsupported: v_bfe_i32`. `binary ` reassembles the fixtures (llvm-mc 19 here; the CI job passes llvm-mc 15). The `draw` mode compiles the translated pair with FXC and DXC and draws one pixel per four input sets through `offscreen_check --startup-flat-param`; the inputs travel as flat vertex parameters so the compilers cannot fold them. It also draws the first set of each operation with the mutated lowering and requires the mutated words in the readback. The draw mode has not been run on WARP or hardware yet; the evaluator and reference results above come from Linux. Tests: `startup_gfx2hlsl_bit_alu_controls`, `startup_gfx2hlsl_bit_alu_warp` and `startup_gfx2hlsl_bit_alu_hardware`. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) + ## Desktop audio render sink `startup_audio_output` drives a small WASAPI shared-mode render sink ([`audio_sink.h`](../src/startup_stubs/audio_sink.h)) with generated PCM blocks. It is the first slice of [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145). The sink takes `submit(format, frames, bytes)`, converts the block to the endpoint mix format (32-bit float or 16-bit PCM only) and records the first accepted block, the submitted format, per-block frame counts and peaks, consumed frames (submitted minus `GetCurrentPadding`), the `IAudioClock` position, the drained interval and the recovery. The fixture runs three cases in one process: no submission; eight 40 ms blocks with distinct amplitudes, one of them intentionally silent; and a producer that withholds the next block until the queue is empty, then resumes. diff --git a/tests/startup_gfx2hlsl_bit_alu_check.py b/tests/startup_gfx2hlsl_bit_alu_check.py new file mode 100644 index 000000000..87240a4dc --- /dev/null +++ b/tests/startup_gfx2hlsl_bit_alu_check.py @@ -0,0 +1,398 @@ +"""Per-lane bit operations in tools/startup/gfx2hlsl.py: v_bfe_i32, v_bcnt_u32_b32, v_ffbl_b32, v_ffbh_u32, +v_ffbh_i32 and v_bfrev_b32. + + (no arguments) translation controls, pure Python + binary reassemble the fixture sources and compare them with the words below + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input sets and compare the four result words + +The pixel fixture reads three flat parameters (v0..v3, v4..v7, v8..v11), applies one operation to each of the four +lanes (VOP1 operations alternate the e32 and e64 encodings) and exports v12..v15 to mrt0. The vertex stage places the +inputs in the parameters, so the pixel stage cannot fold them. + +Every result is compared with a reference written from the ISA description with plain integer arithmetic, string +reversal and bit loops, not with the lowering's own expressions. The translated text is evaluated on the CPU by a +small HLSL integer evaluator over a grid that includes every bfe offset and width. Each lowering also has a mutation +(no 31 minus, unsigned shift, no addend, wrong zero result, no reversal) that must read a wrong word. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import VS_SOURCE, VS_WORDS, assemble, compile_hlsl, draw, root_blob # noqa: E402 + +MASK = 0xffffffff + + +def ref_bfe_i32(x, off, width): + off, width = off & 31, width & 31 + if width == 0: + return 0 + field = ((x - (1 << 32) if x >> 31 else x) >> off) & ((1 << width) - 1) + return (field - (1 << width) if field >> (width - 1) else field) & MASK + + +def ref_ffbh_i32(x): + return next((k for k in range(32) if (x >> (31 - k) & 1) != x >> 31), MASK) + + +# mnemonic -> (source count, VOP1 so the e32 and e64 spellings both exist, reference) +OPS = { + 'v_bfe_i32': (3, False, ref_bfe_i32), + 'v_bcnt_u32_b32': (2, False, lambda x, y: (bin(x).count('1') + y) & MASK), + 'v_ffbl_b32': (1, True, lambda x: next((i for i in range(32) if x >> i & 1), MASK)), + 'v_ffbh_u32': (1, True, lambda x: next((k for k in range(32) if x >> (31 - k) & 1), MASK)), + 'v_ffbh_i32': (1, True, ref_ffbh_i32), + 'v_bfrev_b32': (1, True, lambda x: int('{:032b}'.format(x)[::-1], 2)), +} +# mnemonic -> (pattern in the translated text, replacement): a wrong lowering of the same operation +MUTATIONS = { + 'v_bfe_i32': (r'asuint\(asint\(', 'asuint(('), # the field is not sign-extended + 'v_bcnt_u32_b32': (r'countbits\((v\d+)\) \+ v\d+', r'countbits(\1)'), # the addend is dropped + 'v_ffbl_b32': (r'firstbitlow\((v\d+)\)', r'(\1 == 0u ? 0u : firstbitlow(\1))'), # zero reads 0 + 'v_ffbh_u32': (r'31u - firstbithigh', 'firstbithigh'), # counts from the low end + 'v_ffbh_i32': (r'asint\((v\d+)\) < 0 \? ~v\d+ : v\d+', r'\1'), # negative values scanned as is + 'v_bfrev_b32': (r'reversebits\((v\d+)\)', r'\1'), # not reversed +} +SPECIAL = [0, 1, 2, 3, 0x7f, 0x80, 0xff, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffffe, MASK, 0x55555555, + 0xaaaaaaaa, 0x12345678, 0xdeadbeef, 0x00ff0000] +BITS = SPECIAL + [1 << k for k in range(32)] + [~(1 << k) & MASK for k in range(32)] +GRID = { + 'v_bfe_i32': [(x, off, w) for x in SPECIAL for off in range(32) for w in range(32)] + + [(x, off, w) for x in SPECIAL for off, w in ((32, 33), (63, 0xffffffe5), (0x25, 0x1f))], + 'v_bcnt_u32_b32': [(x, y, 0) for x in BITS for y in (0, 1, 32, MASK)], +} +for _name, (_arity, _vop1, _ref) in OPS.items(): + GRID.setdefault(_name, [(x, 0, 0) for x in BITS]) +# Four input sets per draw: (src0, src1, src2) per lane. The first set separates every mutation from the reference. +DRAW = { + 'v_bfe_i32': [(0x80, 0, 8), (0x80000000, 31, 1), (0x12345678, 8, 0), (0xdeadbeef, 20, 31), + (0xf0, 4, 4), (0x7f, 0, 8), (0x80000000, 16, 16), (MASK, 28, 4), + (0x00ff0000, 16, 8), (0x00800000, 16, 8), (0x12345678, 32, 5), (0xdeadbeef, 5, 37)], + 'v_bcnt_u32_b32': [(0, 0, 0), (0xff, 5, 0), (MASK, MASK, 0), (0x80000001, 1, 0), + (0x55555555, 0, 0), (0, MASK, 0), (0xf0f0f0f0, 7, 0), (0x00010000, 0x80000000, 0)], +} +for _name in ('v_ffbl_b32', 'v_ffbh_u32', 'v_ffbh_i32', 'v_bfrev_b32'): + DRAW[_name] = [(x, 0, 0) for x in (0, 0x100, 0x80000000, 0xfffffff0, 1, MASK, 0x7fffffff, 0xdeadbeef, + 0x00010000, 0x80000001, 0x0000ff00, 0xf0000000)] + +PRE_WORDS = bytes.fromhex( + '0203fcbe020002c8020106c802020ac802030ec8020412c8020516c802061ac8' + '02071ec8020822c8020926c8020a2ac8020b2ec8') +POST_WORDS = bytes.fromhex('0f1800f80c0d0e0f000081bf') +BODY_WORDS = { + 'v_bfe_i32': bytes.fromhex( + '0c0049d5000922040d0049d5010b26040e0049d5020d2a040f0049d5030f2e04'), + 'v_bcnt_u32_b32': bytes.fromhex( + '0c0064d7000902000d0064d7010b02000e0064d7020d02000f0064d7030f0200'), + 'v_ffbl_b32': bytes.fromhex( + '0075187e0d00bad50101000002751c7e0f00bad503010000'), + 'v_ffbh_u32': bytes.fromhex( + '0073187e0d00b9d50101000002731c7e0f00b9d503010000'), + 'v_ffbh_i32': bytes.fromhex( + '0077187e0d00bbd50101000002771c7e0f00bbd503010000'), + 'v_bfrev_b32': bytes.fromhex( + '0071187e0d00b8d50101000002711c7e0f00b8d503010000'), +} +PRE_SOURCE = 's_mov_b32 m0, s2\n' + ''.join('v_interp_mov_f32 v%d, p0, attr%d.%s\n' % (4 * p + c, p, 'xyzw'[c]) + for p in range(3) for c in range(4)) +POST_SOURCE = 'exp mrt0 v12, v13, v14, v15 done vm\ns_endpgm\n' + + +def body_source(op): + arity, vop1, _ = OPS[op] + lines = [] + for lane in range(4): + sources = ', '.join('v%d' % (4 * s + lane) for s in range(arity)) + lines.append('%s%s v%d, %s\n' % (op, '_e64' if vop1 and lane % 2 else '', 12 + lane, sources)) + return ''.join(lines) + + +def ps_words(op): + return PRE_WORDS + BODY_WORDS[op] + POST_WORDS + + +# The vertex stage: the recorded full-screen triangle prefix, then 12 literals in v11..v22 exported as param0..2. +def mov_literal(reg, value): + """v_mov_b32 reg, value with the operand coding llvm-mc picks: an inline constant when there is one.""" + inline = {0x3f000000: 0xf0, 0xbf000000: 0xf1, 0x3f800000: 0xf2, 0xbf800000: 0xf3, 0x40000000: 0xf4, + 0xc0000000: 0xf5, 0x40800000: 0xf6, 0xc0800000: 0xf7, 0x3e22f983: 0xf8} + code = inline.get(value, 0x80 + value if value <= 64 else 0xc0 + (1 << 32) - value if value >= MASK - 15 else None) + if code is not None: + return struct.pack('>|<=|>=|==|!=|\|\||[-+*&|^~!<>?:(),])') +LEVELS = [['||'], ['|'], ['^'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*']] + + +def signed(v): + return v - (1 << 32) if v >> 31 else v + + +class Expr: + def __init__(self, text): + self.tokens = TOKEN.findall(text) + assert ''.join(self.tokens) == re.sub(r'\s+', '', text), text + self.pos = 0 + self.tree = self.ternary() + assert self.pos == len(self.tokens), text + + def peek(self): + return self.tokens[self.pos] if self.pos < len(self.tokens) else None + + def take(self): + self.pos += 1 + return self.tokens[self.pos - 1] + + def ternary(self): + cond = self.binary(0) + if self.peek() != '?': + return cond + self.take() + yes = self.ternary() + assert self.take() == ':' + return ('?', cond, yes, self.ternary()) + + def binary(self, level): + if level == len(LEVELS): + return self.unary() + node = self.binary(level + 1) + while self.peek() in LEVELS[level]: + op = self.take() + node = (op, node, self.binary(level + 1)) + return node + + def unary(self): + token = self.take() + if token in ('~', '-', '!'): + return ('u' + token, self.unary()) + if token == '(': + node = self.ternary() + assert self.take() == ')' + return node + if token[0].isdigit(): + return ('num', int(token.rstrip('u'), 0), not token.endswith('u')) + if self.peek() != '(': + return ('var', token) + self.take() + args = [self.ternary()] + while self.peek() == ',': + self.take() + args.append(self.ternary()) + assert self.take() == ')' + return ('call', token, args) + + def run(self, env, node=None): + node = node or self.tree + kind = node[0] + if kind == 'num': + return node[1] & MASK, node[2] + if kind == 'var': + return env[node[1]], False + if kind == '?': + return self.run(env, node[2] if self.run(env, node[1])[0] else node[3]) + if kind == 'call': + return self.call(node[1], [self.run(env, a) for a in node[2]]) + if kind[0] == 'u' and len(node) == 2: + v, s = self.run(env, node[1]) + return {'u~': ~v, 'u-': -v, 'u!': int(v == 0)}[kind] & MASK, s + (a, sa), (b, sb) = self.run(env, node[1]), self.run(env, node[2]) + both = sa and sb + if kind in ('<<', '>>'): + count = b & 31 + return ((a << count) & MASK if kind == '<<' else (signed(a) >> count if sa else a >> count) & MASK), sa + if kind in ('==', '!=', '<', '>', '<=', '>='): + x, y = (signed(a), signed(b)) if both else (a, b) + return int({'==': x == y, '!=': x != y, '<': x < y, '>': x > y, '<=': x <= y, '>=': x >= y}[kind]), True + if kind == '||': + return int(bool(a or b)), True + return {'|': a | b, '^': a ^ b, '&': a & b, '+': a + b, '-': a - b, '*': a * b}[kind] & MASK, both + + @staticmethod + def call(name, args): + (v, s), rest = args[0], args[1:] + if name in ('asint', 'int'): + return v, True + if name in ('asuint', 'uint'): + return v, False + if name == 'min': + assert not s and not rest[0][1] + return min(v, rest[0][0]), False + assert not s, name # the lowering only scans unsigned values + return {'countbits': bin(v).count('1'), 'reversebits': int('{:032b}'.format(v)[::-1], 2), + 'firstbitlow': (v & -v).bit_length() - 1 if v else MASK, + 'firstbithigh': v.bit_length() - 1 if v else MASK}[name] & MASK, False + + +def lane_expressions(ps_text): + found = re.findall(r'^\s*v(1[2-5]) = (.*);$', ps_text, re.M) + assert [r for r, _ in found] == ['12', '13', '14', '15'], found + return [Expr(text) for _, text in found] + + +def lane_results(exprs, sets): + return [e.run({'v%d' % (4 * s + lane): x[s] for s in range(3)})[0] for lane, (e, x) in enumerate(zip(exprs, sets))] + + +def translate(op, mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()) + text = pipe.hlsl_ps() + if mutate: + pattern, replacement = MUTATIONS[op] + mutated = re.sub(pattern, replacement, text) + assert mutated != text, op + text = mutated + return pipe, text + + +def first_mismatch(op, text): + """The first input whose lane result differs from the reference, or None.""" + exprs, reference = lane_expressions(text), OPS[op][2] + for index, inputs in enumerate(GRID[op]): + lane = index % 4 + got = exprs[lane].run({'v%d' % (4 * s + lane): inputs[s] for s in range(3)})[0] + if got != reference(*inputs[:OPS[op][0]]): + return lane, inputs, got + return None + + +def check(label, ok): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + raise AssertionError(label) + + +class Probe(G.Stage): + """A Stage with no pipeline: enough state for one instruction to be translated.""" + + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + + +def refused(assembly): + try: + Probe().one(assembly.split(' ', 1)[0], assembly) + except G.Unsupported: + return True + return False + + +def controls(): + for op in OPS: + pipe, text = translate(op) + check('%s: %d inputs match the reference (e32 and e64 lanes)' % (op, len(GRID[op])), + first_mismatch(op, text) is None) + found = first_mismatch(op, translate(op, True)[1]) + check('%s: mutation reads a wrong word %s' % (op, found), found is not None) + first = DRAW[op][:4] + wrong = lane_results(lane_expressions(translate(op, True)[1]), first) + check('%s: draw set 0 exposes the mutation' % op, + wrong != [OPS[op][2](*x[:OPS[op][0]]) for x in first]) + # Source-built shader texts name the operands the evaluator reads: v_bfe_i32 field values by hand. + exprs = lane_expressions(translate('v_bfe_i32')[1]) + check('bfe: offset 0 width 8 of 0x80 is -128, width 0 is 0, offset+width above 32 follows bit 31', + lane_results(exprs, [(0x80, 0, 8), (0x12345678, 8, 0), (0x80000000, 16, 31), (0x7fffffff, 31, 31)]) + == [0xffffff80, 0, 0xffff8000, 0]) + check('the same forms without a modifier or operand error translate', not any(refused(a) for a in ( + 'v_ffbh_i32_e64 v1, v2', 'v_bfe_i32 v1, v2, v3, v4', 'v_bcnt_u32_b32 v1, v2, v3', 'v_bfrev_b32 v1, v2'))) + check('modifiers refused', all(refused(a) for a in ( + 'v_ffbh_u32_e64 v1, v2 clamp', 'v_bfe_i32 v1, v2, v3, v4 clamp', 'v_bcnt_u32_b32 v1, v2, v3 clamp', + 'v_ffbl_b32_e64 v1, v2 mul:2', 'v_bfrev_b32_e64 v1, -v2', 'v_ffbh_i32_e64 v1, |v2|', + 'v_bfe_i32 v1, v2, v3, v4 op_sel:[1,0,0,0]'))) + check('wrong operand count refused', all(refused(a) for a in ( + 'v_bfe_i32 v1, v2, v3', 'v_bcnt_u32_b32 v1, v2', 'v_ffbl_b32 v1, v2, v3', 'v_bfrev_b32 v1'))) + + +def check_binary(llvm_mc): + for op in OPS: + built = assemble(llvm_mc, body_source(op)) + if built != BODY_WORDS[op]: + raise AssertionError('%s: assembled %s, recorded %s' % (op, built.hex(), BODY_WORDS[op].hex())) + for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + if assemble(llvm_mc, source) != words: + raise AssertionError('%s fixture differs from llvm-mc' % name) + for sets in (DRAW[op][i:i + 4] for op in DRAW for i in range(0, len(DRAW[op]), 4)): + if assemble(llvm_mc, vs_source(sets)) != vs_words(sets): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (sets,)) + print('fixture words match llvm-mc') + + +def words_text(values): + return ','.join('%08x' % v for v in values) + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for op, sets in DRAW.items(): + reference = OPS[op][2] + good_ps = compile_hlsl(compiler, kind, translate(op)[1], 'ps_%s_%s' % (op, kind), ps_profile, directory) + for index in range(0, len(sets), 4): + chunk = sets[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), ps_words(op), root_blob()).hlsl_vs(), + 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) + expected = words_text(reference(*x[:OPS[op][0]]) for x in chunk) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError('%s %s inputs %s\n%s\n%s' % (kind, op, chunk, run.stdout, run.stderr)) + print('%s %s %s: %s' % (kind, op, [tuple('%x' % v for v in x[:OPS[op][0]]) for x in chunk], expected), + flush=True) + if index: + continue + # The same draw with the mutated lowering must read the mutated words, not the reference. + text = translate(op, True)[1] + wrong = words_text(lane_results(lane_expressions(text), chunk)) + bad_ps = compile_hlsl(compiler, kind, text, 'mutated_%s_%s' % (op, kind), ps_profile, directory) + run = draw(renderer, adapter, vs, bad_ps, expected) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s %s mutation did not read %s\n%s\n%s' % (kind, op, wrong, run.stdout, run.stderr)) + print('%s %s mutation: fails as expected, reads %s' % (kind, op, wrong), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index c922e52f4..ded243b07 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -356,6 +356,8 @@ def one(self, name, asm): arity, text = VEC_U[base] if mods: raise Unsupported('%s with %s' % (base, mods)) + if len(ops) != arity + 1: + raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), arity + 1)) return self.set_v(reg_range(ops[0])[1], text.format(*[self.u(o) for o in ops[1:1 + arity]])) if base in SCA: return self.scalar(base, ops) @@ -972,6 +974,16 @@ def declarations(self): 'v_or3_b32': (3, '{0} | {1} | {2}'), 'v_and_or_b32': (3, '({0} & {1}) | {2}'), 'v_lshl_or_b32': (3, '({0} << ({1} & 31)) | {2}'), 'v_xad_u32': (3, '({0} ^ {1}) + {2}'), 'v_bfi_b32': (3, '({0} & {1}) | (~{0} & {2})'), 'v_mul_u32_u24': (2, '({0} & 0xffffffu) * ({1} & 0xffffffu)'), + # Per-lane bit operations (AMD RDNA 2 ISA reference). The bitscan results count from the most significant + # bit for the "h" forms and read 0xffffffff when no bit qualifies; firstbitlow(0) is already 0xffffffff. + # v_bfe_i32 extracts a field at S1[4:0] of width S2[4:0] (0 reads 0) and sign-extends it from its top bit, + # taking the bits above bit 31 as copies of bit 31; v_bcnt_u32_b32 adds S1 to the population count of S0. + 'v_bfe_i32': (3, '(({2} & 31u) == 0u ? 0u : asuint(asint({0} << (32u - min(({1} & 31u) + ({2} & 31u), 32u))) ' + '>> (32u - min(({1} & 31u) + ({2} & 31u), 32u) + ({1} & 31u))))'), + 'v_bcnt_u32_b32': (2, 'countbits({0}) + {1}'), 'v_ffbl_b32': (1, 'firstbitlow({0})'), + 'v_ffbh_u32': (1, '({0} == 0u ? 0xffffffffu : 31u - firstbithigh({0}))'), + 'v_ffbh_i32': (1, '({0} == 0u || {0} == 0xffffffffu ? 0xffffffffu : 31u - firstbithigh(asint({0}) < 0 ? ~{0} : {0}))'), + 'v_bfrev_b32': (1, 'reversebits({0})'), } # scalar ops: (expression over uint sources, SCC rule with $ for the result or None) SCA = { From f9033a9bbdb0c9bb2f80f882688b436b301046d0 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:34:02 +0100 Subject: [PATCH 043/775] fix: publish the APU heap under one lock, keep the 16-byte alignment fallback, test a guaranteed no-fit --- docs/startup-runtime.md | 6 ++-- src/startup_stubs/acphal.cpp | 30 +++++++++------- tests/startup_acphal_apu_free.cpp | 57 ++++++++++++++++++++++--------- 3 files changed, 62 insertions(+), 31 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 475de20ec..c488bab5c 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -470,8 +470,10 @@ heap is a first-fit free list in a static table of 4096 extents, guarded by one block back and merges it with free neighbours, so streaming code that allocates and frees repeatedly no longer exhausts the heap. While nothing has been freed the offsets are the ones a bump allocator hands out. -- A block is aligned in address (a power of two, 16 at least; 0 means 16). Size and alignment are 32 bits. -- Null output is `E_POINTER`; size 0 or an alignment that is not a power of two is `E_INVALIDARG`; no +- A block is aligned in address (a power of two, 16 at least; 0, anything below 16 and a value that is not a power of two + all mean 16). Size and alignment are 32 bits. `ApuCreateHeap` creates and publishes the heap under one lock, so + competing first calls cannot reset a heap that already has live blocks. +- Null output is `E_POINTER`; size 0 is `E_INVALIDARG`; no room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and the optional APU-address output as they were, and writes null to the virtual-address output when non-null. - A block that is reused is zeroed, as fresh heap memory is. diff --git a/src/startup_stubs/acphal.cpp b/src/startup_stubs/acphal.cpp index 6099de64d..59108e0fc 100644 --- a/src/startup_stubs/acphal.cpp +++ b/src/startup_stubs/acphal.cpp @@ -82,8 +82,8 @@ bool heap_give(const void* virtual_address) { bool done = false; const std::uintptr_t address = reinterpret_cast(virtual_address); - const std::uintptr_t base = reinterpret_cast(heap_base); AcquireSRWLockExclusive(&heap_lock); + const std::uintptr_t base = reinterpret_cast(heap_base); if (heap_base && address >= base + heap_start && address - base < heap_bytes) { const u64 offset = address - base; std::size_t lo = 0, hi = extent_count; @@ -149,17 +149,24 @@ extern "C" __declspec(noinline) long ApuCreateHeap(u64 rcx, u64 rdx, u64 r8, u64 x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuCreateHeap", 4, rcx, rdx, r8, r9, _ReturnAddress()); const u64 cached = static_cast(rcx), non_cached = static_cast(rdx); long hr = 0; + // Creation and publication are one locked step: base, size and the initial free extent become + // visible together, and a repeat call finds the heap and leaves live blocks alone. + AcquireSRWLockExclusive(&heap_lock); if (!heap_base) { const u64 bytes = ((cached + non_cached) + 0xFFFF) & ~u64{0xFFFF}; - heap_base = static_cast(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); - AcquireSRWLockExclusive(&heap_lock); - heap_bytes = heap_base ? bytes : 0; - heap_reset(); - ReleaseSRWLockExclusive(&heap_lock); - if (!heap_base) hr = static_cast(0x8007000E); // E_OUTOFMEMORY + void* memory = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (memory) { + heap_bytes = bytes; + heap_reset(); + heap_base = static_cast(memory); + } else { + hr = static_cast(0x8007000E); // E_OUTOFMEMORY + } } + unsigned char* const published = heap_base; + ReleaseSRWLockExclusive(&heap_lock); x2w_local::logf("x2w-audio ApuCreateHeap cached=0x%llx non_cached=0x%llx -> 0x%08lx base=%p", cached, non_cached, - static_cast(hr), static_cast(heap_base)); + static_cast(hr), static_cast(published)); return hr; } @@ -218,8 +225,7 @@ extern "C" __declspec(noinline) long AcpHalCreate(u64 rcx, u64 rdx, u64 r8, u64 // ApuAlloc(&virtualAddress, apuAddress* or null, size, alignment, flags) -> HRESULT (first call: // size 0x222e00, alignment 0x800, null APU-address output). Size and alignment are taken as 32 bits. // First fit; ApuFree returns blocks, and a reused block is zeroed as fresh heap memory is. -// A null output is E_POINTER, size 0 or an alignment that is not a power of two is E_INVALIDARG -// (0 and anything below 16 mean 16), and no room is E_OUTOFMEMORY; a failure leaves the heap as it was. +// A null output is E_POINTER, size 0 is E_INVALIDARG; an alignment below 16 or not a power of two means 16, and no room is E_OUTOFMEMORY; a failure leaves the heap as it was. extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint32_t* apu_address, u64 size, u64 alignment, u64 flags) { @@ -228,8 +234,8 @@ extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint3 reinterpret_cast(apu_address), size, alignment, _ReturnAddress()); const u64 bytes = static_cast(size); u64 align = static_cast(alignment); - if (align < 16) align = 16; - const bool valid = bytes && !(align & (align - 1)); + if (align < 16 || (align & (align - 1))) align = 16; + const bool valid = bytes != 0; unsigned char* memory = virtual_address && valid ? heap_take(bytes, align) : nullptr; const long hr = memory ? 0 : static_cast(!virtual_address ? 0x80004003 : valid ? 0x8007000E : 0x80070057); if (virtual_address) *virtual_address = memory; diff --git a/tests/startup_acphal_apu_free.cpp b/tests/startup_acphal_apu_free.cpp index 60ab7b0bb..1f66df18d 100644 --- a/tests/startup_acphal_apu_free.cpp +++ b/tests/startup_acphal_apu_free.cpp @@ -141,23 +141,15 @@ void bad_requests() check(take(&out, ~u64{0}, 16, &apu) == no_memory && !out, "size 2^64-1 is cut to 32 bits"); check(take(&out, 0, 16, &apu) == invalid && !out && apu == 0xDEADBEEF, "size 0"); check(take(&out, 0x100000000ull, 16, &apu) == invalid && !out, "size 2^32 is size 0"); - check(take(&out, 64, 24, &apu) == invalid && !out && apu == 0xDEADBEEF, "alignment 24"); - check(take(&out, 64, 0xFFFFFFFFull, &apu) == invalid && !out, "alignment 2^32-1"); - void* probe = take_ok(16); - const auto probe_addr = reinterpret_cast(probe); - check(free_fn(probe) == ok, "free probe"); - const std::uint64_t big_align = 0x80000000ull; - const std::uintptr_t aligned_addr = (probe_addr + big_align - 1) & ~(big_align - 1); - const bool big_align_fits = aligned_addr >= probe_addr && (aligned_addr - probe_addr) + 64 <= usable; - out = const_cast(sentinel); - const long big_hr = take(&out, 64, big_align, &apu); - if (big_align_fits) { - check(big_hr == ok && out && reinterpret_cast(out) == aligned_addr, - "alignment 2 GiB succeeds when heap straddles boundary"); - check(free_fn(out) == ok, "free 2 GiB aligned block"); - } else { - check(big_hr == no_memory && !out && apu == 0xDEADBEEF, "alignment 2 GiB cannot be met"); + // Not a power of two means 16, so these succeed and honour 16. + for (u64 odd : {u64{24}, u64{0xFFFFFFFF}, u64{3}}) { + void* r = take_ok(64, odd); + check(reinterpret_cast(r) % 16 == 0, "non-power-of-two alignment falls back to 16"); + check(free_fn(r) == ok, "free fallback block"); } + // No placement can satisfy a heap-sized block at 2 GiB alignment plus 16 spare bytes. + out = const_cast(sentinel); + check(take(&out, usable + 16, 0x80000000ull, &apu) == no_memory && !out && apu == 0xDEADBEEF, "no-fit request with 2 GiB alignment"); check_empty("refused requests"); void* p = take_ok(0x40, 0); // 0 means the default of 16 @@ -260,6 +252,37 @@ void concurrent() check(live.blocks.empty(), "every block was released"); check_empty("concurrent run"); } +// Competing first-time creators: every caller gets a block right after its create returns and keeps it +// while the others are still creating. A second creation that reset the table would hand out a +// block that overlaps a live one, or leave a live block unfreeable. +void first_creation(CreateFn create) +{ + constexpr unsigned callers = 4; + std::atomic go{false}; + std::atomic bad{0}; + void* blocks[callers] = {}; + std::vector threads; + for (unsigned id = 0; id < callers; ++id) + threads.emplace_back([&, id] { + while (!go.load()) std::this_thread::yield(); + if (create(heap_size, 0) != ok) ++bad; + void* p = nullptr; + if (take(&p, 0x1000, 16) != ok || !p) ++bad; + blocks[id] = p; + }); + go = true; + for (auto& t : threads) t.join(); + check(bad.load() == 0, "concurrent first ApuCreateHeap calls and allocations succeed"); + for (unsigned i = 0; i < callers; ++i) + for (unsigned j = i + 1; j < callers; ++j) + check(blocks[i] != blocks[j], "competing creators got distinct blocks"); + check(create(heap_size, 0) == ok, "repeat ApuCreateHeap"); + void* extra = take_ok(0x1000); + for (void* b : blocks) check(extra != b, "block taken after a repeat creation does not reuse a live block"); + for (void* b : blocks) check(free_fn(b) == ok, "live block survives competing creation and frees"); + check(free_fn(extra) == ok, "free extra"); + check_empty("first creation"); +} } // namespace int main(int argc, char** argv) @@ -275,7 +298,7 @@ int main(int argc, char** argv) if (!alloc_fn || !free_fn || !map_fn || !create) return std::printf("FAIL: missing export\n"), 2; void* none = nullptr; check(take(&none, 64) == no_memory && !none, "no heap yet"); - check(create(heap_size, 0) == ok, "ApuCreateHeap"); + first_creation(create); churn_beyond_capacity(); reuse_and_alignment(); coalescing(); From 75908557c812132990b292fe9734fbf0ddfff713 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:39:13 +0100 Subject: [PATCH 044/775] test: define each bit-op mutation independently and subtract the bcnt addend The v_bcnt_u32_b32 mutation dropped the addend, so the mutated pixel stage no longer read the second flat parameter set and the WARP readback was all zero. The mutation now subtracts the addend (same inputs read as the correct lowering). The expected mutated words come from MUTATION_REF, a plain integer definition of each of the six mutations, and the CPU evaluator on the mutated text must agree with it over the whole grid. --- docs/experiments.md | 2 +- tests/startup_gfx2hlsl_bit_alu_check.py | 34 ++++++++++++++++++++----- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 35c7b263f..75a9d836b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9482,7 +9482,7 @@ measurement on hardware or in a Windows run backs the descriptions. `v_interp_p1 `tools/startup/gfx2hlsl.py` now lowers six gfx1013 per-lane bit operations that it used to refuse: `v_bfe_i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32`, `v_ffbh_i32` and `v_bfrev_b32`. They become single HLSL expressions, so no helper function is added to the output: `countbits(a) + b`, `firstbitlow(a)`, `reversebits(a)`, and, for the two high scans, `a == 0u ? 0xffffffffu : 31u - firstbithigh(a)` (the signed form scans `~a` for a negative value and reads 0xffffffff for 0 and -1). `v_bfe_i32` takes the offset from bits 4:0 of source 1 and the width from bits 4:0 of source 2, reads 0 for a width of 0, and sign-extends the field from its top bit; when offset plus width passes 32, the bits above bit 31 repeat bit 31, which is an arithmetic shift of the whole word. The formulas and edge cases are the ones `tools/pixel_aot.py` already draws on WARP. `v_bfe_i32` and `v_bcnt_u32_b32` exist only as VOP3 on gfx1013 (llvm-mc 19 rejects `_e32`); the other four assemble in both `_e32` and `_e64`. Source modifiers, `clamp`, output modifiers, `op_sel` and a wrong operand count are refused with `Unsupported`; the operand count is now checked for every integer operation in this table, where a missing operand used to raise `IndexError`. Not lowered here: the 64-bit carry forms, `v_bfm_b32`, the 24-bit multiplies and `v_alignbit_b32`. -`tests/startup_gfx2hlsl_bit_alu_check.py` translates a source-built pixel stage that applies each operation to four lanes (the VOP1 operations alternate `_e32` and `_e64`) and evaluates the generated text with a small 32-bit HLSL evaluator against a reference written from the ISA description with bit loops, string reversal and integer arithmetic. The grid holds 17,459 inputs for `v_bfe_i32` (every offset and width 0 to 31 for 17 base words, plus offsets and widths above 31), 324 for `v_bcnt_u32_b32` and 81 for each scan. Each lowering also has a mutation that must read a wrong word: no sign extension, no addend, 0 instead of 0xffffffff for zero, no `31u -`, a negative value scanned unchanged, and no bit reversal. On `origin/main` the check fails with `Unsupported: v_bfe_i32`. `binary ` reassembles the fixtures (llvm-mc 19 here; the CI job passes llvm-mc 15). The `draw` mode compiles the translated pair with FXC and DXC and draws one pixel per four input sets through `offscreen_check --startup-flat-param`; the inputs travel as flat vertex parameters so the compilers cannot fold them. It also draws the first set of each operation with the mutated lowering and requires the mutated words in the readback. The draw mode has not been run on WARP or hardware yet; the evaluator and reference results above come from Linux. Tests: `startup_gfx2hlsl_bit_alu_controls`, `startup_gfx2hlsl_bit_alu_warp` and `startup_gfx2hlsl_bit_alu_hardware`. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) +`tests/startup_gfx2hlsl_bit_alu_check.py` translates a source-built pixel stage that applies each operation to four lanes (the VOP1 operations alternate `_e32` and `_e64`) and evaluates the generated text with a small 32-bit HLSL evaluator against a reference written from the ISA description with bit loops, string reversal and integer arithmetic. The grid holds 17,459 inputs for `v_bfe_i32` (every offset and width 0 to 31 for 17 base words, plus offsets and widths above 31), 324 for `v_bcnt_u32_b32` and 81 for each scan. Each lowering also has a mutation that must read a wrong word: no sign extension, a subtracted addend, 0 instead of 0xffffffff for zero, no `31u -`, a negative value scanned unchanged, and no bit reversal. On `origin/main` the check fails with `Unsupported: v_bfe_i32`. `binary ` reassembles the fixtures (llvm-mc 19 here; the CI job passes llvm-mc 15). The `draw` mode compiles the translated pair with FXC and DXC and draws one pixel per four input sets through `offscreen_check --startup-flat-param`; the inputs travel as flat vertex parameters so the compilers cannot fold them. It also draws the first set of each operation with the mutated lowering and requires the mutated words in the readback. The draw mode has not been run on WARP or hardware yet; the evaluator and reference results above come from Linux. Tests: `startup_gfx2hlsl_bit_alu_controls`, `startup_gfx2hlsl_bit_alu_warp` and `startup_gfx2hlsl_bit_alu_hardware`. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) ## Desktop audio render sink diff --git a/tests/startup_gfx2hlsl_bit_alu_check.py b/tests/startup_gfx2hlsl_bit_alu_check.py index 87240a4dc..796dd78b4 100644 --- a/tests/startup_gfx2hlsl_bit_alu_check.py +++ b/tests/startup_gfx2hlsl_bit_alu_check.py @@ -14,7 +14,10 @@ Every result is compared with a reference written from the ISA description with plain integer arithmetic, string reversal and bit loops, not with the lowering's own expressions. The translated text is evaluated on the CPU by a small HLSL integer evaluator over a grid that includes every bfe offset and width. Each lowering also has a mutation -(no 31 minus, unsigned shift, no addend, wrong zero result, no reversal) that must read a wrong word. +(no 31 minus, unsigned shift, subtracted addend, wrong zero result, no reversal) that must read a wrong word. The words +the mutated draw must read come from MUTATION_REF, a plain integer definition of each mutation, and the evaluator on +the mutated text must agree with it. A mutation that keeps the same inputs read as the correct lowering is used so +the pixel stage has the same interface in both draws. """ import re import struct @@ -55,12 +58,22 @@ def ref_ffbh_i32(x): # mnemonic -> (pattern in the translated text, replacement): a wrong lowering of the same operation MUTATIONS = { 'v_bfe_i32': (r'asuint\(asint\(', 'asuint(('), # the field is not sign-extended - 'v_bcnt_u32_b32': (r'countbits\((v\d+)\) \+ v\d+', r'countbits(\1)'), # the addend is dropped + 'v_bcnt_u32_b32': (r'countbits\((v\d+)\) \+ (v\d+)', r'countbits(\1) - \2'), # the addend is subtracted 'v_ffbl_b32': (r'firstbitlow\((v\d+)\)', r'(\1 == 0u ? 0u : firstbitlow(\1))'), # zero reads 0 'v_ffbh_u32': (r'31u - firstbithigh', 'firstbithigh'), # counts from the low end 'v_ffbh_i32': (r'asint\((v\d+)\) < 0 \? ~v\d+ : v\d+', r'\1'), # negative values scanned as is 'v_bfrev_b32': (r'reversebits\((v\d+)\)', r'\1'), # not reversed } +# mnemonic -> the word the mutated lowering must produce, defined from the mutation and the inputs with plain integer +# arithmetic (not from the evaluator and not from a readback) +MUTATION_REF = { + 'v_bfe_i32': lambda x, off, w: 0 if w & 31 == 0 else (x >> (off & 31)) & ((1 << (w & 31)) - 1), + 'v_bcnt_u32_b32': lambda x, y: (bin(x).count('1') - y) & MASK, + 'v_ffbl_b32': lambda x: 0 if x == 0 else (x & -x).bit_length() - 1, + 'v_ffbh_u32': lambda x: MASK if x == 0 else x.bit_length() - 1, + 'v_ffbh_i32': lambda x: MASK if x in (0, MASK) else 32 - x.bit_length(), + 'v_bfrev_b32': lambda x: x, +} SPECIAL = [0, 1, 2, 3, 0x7f, 0x80, 0xff, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffffe, MASK, 0x55555555, 0xaaaaaaaa, 0x12345678, 0xdeadbeef, 0x00ff0000] BITS = SPECIAL + [1 << k for k in range(32)] + [~(1 << k) & MASK for k in range(32)] @@ -311,12 +324,19 @@ def controls(): pipe, text = translate(op) check('%s: %d inputs match the reference (e32 and e64 lanes)' % (op, len(GRID[op])), first_mismatch(op, text) is None) - found = first_mismatch(op, translate(op, True)[1]) + mutated = translate(op, True)[1] + found = first_mismatch(op, mutated) check('%s: mutation reads a wrong word %s' % (op, found), found is not None) + arity, mutated_exprs = OPS[op][0], lane_expressions(mutated) + check('%s: the mutated text equals the mutation definition on all %d inputs' % (op, len(GRID[op])), + all(mutated_exprs[i % 4].run({'v%d' % (4 * s + i % 4): x[s] for s in range(3)})[0] + == MUTATION_REF[op](*x[:arity]) for i, x in enumerate(GRID[op]))) first = DRAW[op][:4] - wrong = lane_results(lane_expressions(translate(op, True)[1]), first) - check('%s: draw set 0 exposes the mutation' % op, - wrong != [OPS[op][2](*x[:OPS[op][0]]) for x in first]) + wrong = [MUTATION_REF[op](*x[:arity]) for x in first] + check('%s: draw set 0 mutated words %s differ from the reference and are not all zero' % (op, words_text(wrong)), + wrong != [OPS[op][2](*x[:arity]) for x in first] and any(wrong)) + check('%s: evaluator on the mutated text reads the same words' % op, + lane_results(mutated_exprs, first) == wrong) # Source-built shader texts name the operands the evaluator reads: v_bfe_i32 field values by hand. exprs = lane_expressions(translate('v_bfe_i32')[1]) check('bfe: offset 0 width 8 of 0x80 is -128, width 0 is 0, offset+width above 32 follows bit 31', @@ -373,7 +393,7 @@ def check_draw(dxc, renderer, adapter, fxc=None): continue # The same draw with the mutated lowering must read the mutated words, not the reference. text = translate(op, True)[1] - wrong = words_text(lane_results(lane_expressions(text), chunk)) + wrong = words_text(MUTATION_REF[op](*x[:OPS[op][0]]) for x in chunk) bad_ps = compile_hlsl(compiler, kind, text, 'mutated_%s_%s' % (op, kind), ps_profile, directory) run = draw(renderer, adapter, vs, bad_ps, expected) if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: From 772ac100a416a4c7c5280ce64364960d34d0c971 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 19:26:13 +0800 Subject: [PATCH 045/775] shader: lower four gfx1030 pixel sample offset forms --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 5 + README.md | 1 + docs/experiments.md | 33 ++++++ tests/pixel_sample_offset_check.py | 167 +++++++++++++++++++++++++++++ tools/pixel_aot.py | 59 +++++++--- 6 files changed, 250 insertions(+), 16 deletions(-) create mode 100644 tests/pixel_sample_offset_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b73d82490..252551559 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -38,6 +38,7 @@ jobs: python3 -B tests/sampled_coverage_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/depth_mask_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/pixel_aot_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 + python3 -B tests/pixel_sample_offset_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/pixel_compare_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/compute_store_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/mesh_indexed_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 diff --git a/CMakeLists.txt b/CMakeLists.txt index 480656a3b..ece2d30e6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5718,6 +5718,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_sample_lod_${adapter} PROPERTIES TIMEOUT 60 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sample_lod_${adapter}.txt") + add_test(NAME pixel_aot_sample_offset_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_sample_offset_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_sample_offset_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sample_offset_${adapter}.txt") add_test(NAME pixel_aot_three_way_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" three-way "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 75dad6a6e..07ba9da76 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 formatted UINT buffer reads | Lower [indexed `buffer_load_format_*` with caller-declared RGBA32 UINT](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-reads) and verify one to four channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_format_'` | | gfx1030 formatted D16 UINT writes | Lower [indexed packed `buffer_store_format_d16_x/xy/xyzw`](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-writes) and verify the untouched halfword and record padding. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | gfx1030 formatted UINT buffer writes | Lower [indexed `buffer_store_format_*` with matching caller-declared UINT texels](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-writes) and compare full UAV readback with a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | +| gfx1030 pixel sampling offsets | Lower [four 2D sample offset forms](docs/experiments.md#offline-pixel-shader-recompilation) with a known packed XY displacement. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_offset_' -V` | | Shader census | [Distinguish archive records, header digests and cache-index entries](docs/experiments.md#reporting-shader-census-populations) before choosing a coverage denominator. | `ctest --preset dev --no-tests=error -R "^shader_metadata_census$" -V` | | Shader effect metadata | Inventory the [candidate programs for a named SGD5 effect](docs/experiments.md#candidate-programs-for-a-named-sgd5-effect) using independently located archive ranges. | `ctest --preset dev --no-tests=error -R "^sgd5_effect_candidates$" -V` | | Pipeline readiness | Join explicit pipeline references to the native shader manifest and optionally probe pixel and mesh lowering. [Inputs and WARP control](docs/experiments.md#pipeline-readiness-from-shader-manifests) | `ctest --preset dev -R '^pso_' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index 5f7a5182d..99fb7e0dc 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4981,6 +4981,39 @@ For a single 2D RGBA sample, `image_sample_lz` lowers to `SampleLevel` at level For the same single-texture RGBA profile, `image_sample_l` takes `(u, v, lod)` and lowers to `SampleLevel`; `image_sample_b` takes `(bias, u, v)` and lowers to `SampleBias`. Explicit LOD also accepts defined numeric coordinates, including constant-buffer values. Bias sampling still needs whole-quad UVs for derivatives. Both new forms keep the full `dmask:0xf` requirement. The `pixel_aot_sample_lod_{warp,hardware}` tests compare mips with distinct colors, check an 8 by 8 UV ramp and exercise constant-buffer coordinates without whole-quad mode. Substituting implicit sampling for LOD zero, changing the explicit LOD or bias from one to zero, or swapping the bias sample's UVs must each cause a mismatch. +The single-texture pixel lowerer also accepts four offset forms with +contiguous 32-bit 2D addresses and `dmask:0xf`. Use `--cpu gfx1030` for the +wave64 `gfx1030` pixel profile. The first address word packs +signed six-bit offsets in bits `[5:0]` and `[13:8]`. The following address words +hold UV for `image_sample_o` and `image_sample_lz_o`, bias then UV for +`image_sample_b_o`, and UV then LOD for `image_sample_l_o`. The lowerer requires +a statically known canonical 2D offset and bounds each component to `[-8, 7]`. +It passes the displacement as an immediate `int2` to `Sample`, `SampleBias`, or +`SampleLevel`, using zero LOD for `_lz_o`. The profile assumes matching desktop +texture and sampler bindings and integer mip levels for offset sampling. See +[AMD RDNA 2 ISA §§8.2.4–8.2.5](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) +and [DXIL sampling](https://github.com/microsoft/DirectXShaderCompiler/blob/main/docs/DXIL.rst#texturing). + +The LLVM 15 check round-trips all four `gfx1030` encodings and checks the +CLI output from a source-built container. The draw fixture +reuses the point-clamp sampler, 8×8 UV ramp, and two-color mip texture from the +LOD check. It expects offset `(1, -2)` on the ramp, including edge clamping, +and expects LOD or bias `1` to select mip 1. Zero-offset and zero-LOD or +zero-bias mutations must produce `pixel_mismatch`. A scaled-quad control +checks that `_lz_o` still selects mip 0 when `_o` selects mip 1. Both the offset +and existing LOD cases passed on Windows 11 build 26300.9974 with the Intel +Arc B390 (32.0.101.8509) and Microsoft Basic Render Driver for WARP +(10.0.26100.9818). The debug layer was unavailable on both runs. The four +offset forms appear in each passing offset test's coverage record. + +```bash +python3 -B tests/pixel_sample_offset_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 +``` + +```powershell +ctest --preset dev --no-tests=error -R '^pixel_aot_sample_offset_' -V +``` + Depth-comparison sampling covers one form: `image_sample_c_lz vD, v[a:a+2], ... dmask:0x1 dim:SQ_RSRC_IMG_2D` and its NSA spelling `[vR, vU, vV]`. In RDNA 2 the reference comes before the coordinates. The result lowers to `tex.SampleCmpLevelZero(samp, float2(u, v), reference)` on `Texture2D tex : register(t0)` and `SamplerComparisonState samp : register(s0)`. The four sampler words must still match the caller binding. `comparison_sampler_state()` decodes them, and the generated HLSL names the desktop state it needs in a comment. The compare function comes from word 0 bits 14:12, in the same order as `D3D12_COMPARISON_FUNC` minus one, and the result is `reference OP texel`. One point or bilinear XY filter maps to `D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT` or `..._MIN_MAG_LINEAR_MIP_POINT`. Other values are refused, each with its own message: - X/Y addressing other than `CLAMP_LAST_TEXEL`; - anisotropy, unnormalized coordinates, `MC_COORD_TRUNC` or `FORCE_DEGAMMA`; diff --git a/tests/pixel_sample_offset_check.py b/tests/pixel_sample_offset_check.py new file mode 100644 index 000000000..72a783766 --- /dev/null +++ b/tests/pixel_sample_offset_check.py @@ -0,0 +1,167 @@ +"""Exercise four gfx1030 2D sample forms with immediate texel offsets.""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import assemble +from pixel_aot_check import RAMP, envelope, pixel_aot, translate, write_record +from pixel_sample_lod_check import base_prefix, compile_ps, export16, export_tail, single + + +FORMS = { + "image_sample_o": ("v[7:9]", "Sample"), + "image_sample_b_o": ("v[6:9]", "SampleBias"), + "image_sample_l_o": ("v[7:10]", "SampleLevel"), + "image_sample_lz_o": ("v[7:9]", "SampleLevel"), +} + + +def program(op, *, offset="0x3e01", level="0", quad_scale=False, swap_rg=False): + address, _ = FORMS[op] + offset_register = "v6" if op == "image_sample_b_o" else "v7" + body = [f"v_mov_b32_e32 {offset_register}, {offset}"] + if op == "image_sample_b_o": + body.append(f"v_mov_b32_e32 v7, {level}") + elif op == "image_sample_l_o": + body.append(f"v_mov_b32_e32 v10, {level}") + body.append(f"{op} v[12:15], {address}, s[28:35], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D") + return base_prefix(quad_scale=quad_scale) + body + export_tail(swap_rg=swap_rg) + + +def reject(program, diagnostic): + try: + translate(program) + except ValueError as error: + assert diagnostic in str(error), str(error) + else: + raise AssertionError(f"Expected rejection with {diagnostic!r}") + + +def check_lowering(): + for op, (_, method) in FORMS.items(): + level_arg = {"image_sample_o": "", "image_sample_lz_o": r", 0\.0f"}.get(op, r", alu\d+") + source = translate(program(op)) + call = rf"tex\.{method}\(samp, float2\(uv\.x, uv\.y\){level_arg}, int2\(1, -2\)\);" + assert re.search(call, source), op + op = "image_sample_lz_o" + source = translate(program(op, offset="0x0738")) + assert "int2(-8, 7)" in source + copied = program(op, offset="v6") + copied.insert(copied.index("v_mov_b32_e32 v7, v6"), "v_mov_b32_e32 v6, 0x3e01") + assert "int2(1, -2)" in translate(copied) + reject(program(op, offset="0x8"), "outside the DXIL immediate range") + reject(program(op, offset="0x3700"), "outside the DXIL immediate range") + reject(program(op, offset="0x10000"), "canonical 2D offset word") + reject(program(op, offset="0x40"), "canonical 2D offset word") + undefined = [line for line in program(op) if not line.startswith("v_mov_b32_e32 v7,")] + reject(undefined, "known packed integer word") + runtime = [line.replace("v_mov_b32_e32 v7, 0x3e01", "v_mov_b32_e32 v7, s60") + for line in program(op)] + # Bind a runtime cbuffer value at s60 through the existing constant-descriptor path. + runtime[:len(base_prefix())] = base_prefix(quad_scale=True) + reject(runtime, "known packed integer word") + pending = [line.replace("v[12:15]", "v[7:10]") if line.startswith(op) else line + for line in program(op)] + pending.insert(next(i for i, line in enumerate(pending) if line.startswith(op)) + 1, + next(line for line in program(op) if line.startswith(op))) + reject(pending, "offset used before vmcnt wait") + for old, new, diagnostic in ( + ("v[7:9]", "v[8:9]", "Descriptor or vector width mismatch"), + ("v[7:9]", "[v7, v8, v9]", "Unsupported instruction"), + ("dmask:0xf", "dmask:0x7", "requires dmask:0xf"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_3D", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D a16", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D d16", "Unsupported instruction"), + ("s[40:43]", "s[44:47]", "Unsupported image or sampler binding"), + ): + reject([line.replace(old, new) for line in program(op)], diagnostic) + + +def check_binary(directory, assembler, objcopy, library): + features = "+wavefrontsize64,-wavefrontsize32" + for op in FORMS: + lines = program(op, level="1.0") + data = assemble(directory, assembler, objcopy, lines, cpu="gfx1030", features=features) + decoded = pixel_aot.disassemble(data, library, cpu=b"gfx1030", features=features.encode(), offsets=True) + assert [line for _, line in decoded if line.startswith("image_")] == [ + line for line in lines if line.startswith("image_") + ] + expected = translate(lines) + assert translate(decoded) == expected + + archive = directory / "fixture.bin" + archive.write_bytes(envelope(data)) + output = directory / "fixture.hlsl" + subprocess.run([sys.executable, "-B", pixel_aot.__file__, archive, "fixture", "--llvm", library, + "--cpu", "gfx1030", "--texture-sgpr", "20", "--interp-sgpr", "24", + "--sampler-words", "1", "2", "3", "4", "--constant-descriptor", "0x40", + "--output", output], + check=True, capture_output=True, text=True) + assert output.read_text(encoding="utf-8") == expected + + +def check_compile(directory, compiler): + return {op: compile_ps(compiler, translate(program(op)), directory, op) for op in FORMS} + + +def ramp_case(dx, dy): + out = bytearray(256) # unused b0 constants in the existing pixel renderer + for y in range(8): + for x in range(8): + u = RAMP[max(0, min(7, x + dx))] + v = RAMP[max(0, min(7, y + dy))] + out += struct.pack("<4f", export16(single(u / 255)), export16(single(v / 255)), + export16(single(128 / 255)), 1.0) + return out + + +def draw(renderer, adapter, mode, shader, *args, mismatch=False): + result = subprocess.run([renderer, adapter, mode, shader, *args], capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, end="") + print(result.stderr, end="", file=sys.stderr) + raise SystemExit(77) + if mismatch: + assert result.returncode == 1 and "pixel_mismatch" in result.stderr, (result.stdout, result.stderr) + print(f"Negative control {Path(shader).stem}:\n{result.stderr}", end="") + else: + assert result.returncode == 0, (result.stdout, result.stderr) + print(result.stdout, end="") + + +def check_draw(directory, compiler, renderer, adapter): + case = directory / "offset.case" + case.write_bytes(ramp_case(1, -2)) + for op, shader in check_compile(directory, compiler).items(): + draw(renderer, adapter, "--check-pixel-case", shader, case) + mutant = compile_ps(compiler, translate(program(op, offset="0")), directory, f"{op}_zero_offset") + draw(renderer, adapter, "--check-pixel-case", mutant, case, mismatch=True) + + # The spatial ramp exercises offsets at mip zero. Reuse the two-color texture + # to distinguish a nonzero explicit LOD or bias from accidental mip-zero sampling. + for op in ("image_sample_l_o", "image_sample_b_o"): + for level in ("1.0", "0.0"): + shader = compile_ps(compiler, translate(program(op, level=level)), directory, f"{op}_level_{level}") + draw(renderer, adapter, "--check-pixel-quad-lod", shader, mismatch=level == "0.0") + # A 4x horizontal derivative selects mip 1 for the implicit form. Swap R/G + # so mip 0 from the LZ form matches the renderer's green reference. + for op in ("image_sample_lz_o", "image_sample_o"): + shader = compile_ps(compiler, translate(program(op, quad_scale=True, swap_rg=True)), + directory, f"{op}_quad") + draw(renderer, adapter, "--check-pixel-quad-lod", shader, mismatch=op == "image_sample_o") + write_record(os.environ.get("FORM_COVERAGE_RECORD")) + + +if __name__ == "__main__": + check_lowering() + if len(sys.argv) > 1: + mode, *args = sys.argv[1:] + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="sample-offset-", dir=out) as tmp: + {"binary": check_binary, "compile": check_compile, "draw": check_draw}[mode](Path(tmp), *args) + print("Four 2D sample offset forms checked") diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 72a243015..8a92cdedc 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -75,9 +75,9 @@ def _bounded_code(image, start): return image[start:end] -def _check_two_exits(code, llvm): +def _check_two_exits(code, llvm, *, cpu, features): """Both decoded exits must be reachable from the single entry.""" - instructions = dict(disassemble(code, llvm, offsets=True)) + instructions = dict(disassemble(code, llvm, offsets=True, cpu=cpu, features=features)) exits = [pc for pc, line in instructions.items() if line == "s_endpgm"] if len(exits) != 2 or exits[-1] + 4 != len(code): raise ValueError("Expected two decoded exits") @@ -121,7 +121,8 @@ def _check_two_exits(code, llvm): raise ValueError("Unreachable code or unverified alternate exit") -def native_program(archive: Path, record: str, *, container_sha256: str | None = None, llvm=None) -> tuple[bytes, bytes]: +def native_program(archive: Path, record: str, *, container_sha256: str | None = None, llvm=None, + cpu=b"gfx1013", features=b"") -> tuple[bytes, bytes]: name = record.encode("ascii") if not 0 < len(name) < 255 or b"\0" in name: raise ValueError("Invalid length-prefixed record name") @@ -139,10 +140,10 @@ def native_program(archive: Path, record: str, *, container_sha256: str | None = blob = _read_named_container(data, end) else: blob = _select_named_container(data, needle, container_sha256.lower()) - return blob, container_code(parts(blob)[b"DXIL"], stage=0, llvm=llvm) + return blob, container_code(parts(blob)[b"DXIL"], stage=0, llvm=llvm, cpu=cpu, features=features) -def container_code(program, *, stage, llvm=None): +def container_code(program, *, stage, llvm=None, cpu=b"gfx1013", features=b""): """Extract the stage-specific instruction stream from a DXIL program part.""" if len(program) < 24 or struct.unpack_from("> bit) & 1] if len(channels) == 1: if dst_single is None: @@ -3892,6 +3896,24 @@ def match(pattern): if op != "image_sample" and second_texture_offset is not None: raise ValueError(f"{op} requires a single texture binding") coord_regs = [f"v{n}" for n in coords] + offset_arg = "" + if has_offset: + offset_reg = coord_regs.pop(0) + if offset_reg in sample_dest: + raise ValueError("Sample offset used before vmcnt wait") + value = vector.get(offset_reg) + if not isinstance(value, str) or value not in known_ssa_bits: + raise ValueError("Sample offset must be a known packed integer word") + packed = known_ssa_bits[value] + # RDNA 2 packs signed six-bit X and Y at bits [5:0] and [13:8]. + # Require a canonical 2D word and offsets representable in ps_6_0. + if packed & ~0x3f3f: + raise ValueError("Sample offset must be a canonical 2D offset word") + x = ((packed & 0x3f) ^ 0x20) - 0x20 + y = (((packed >> 8) & 0x3f) ^ 0x20) - 0x20 + if not (-8 <= x <= 7 and -8 <= y <= 7): + raise ValueError("Sample offset is outside the DXIL immediate range [-8, 7]") + offset_arg = f", int2({x}, {y})" if any(reg not in vector for reg in coord_regs): raise ValueError("Unsupported texture coordinate") @@ -3903,21 +3925,21 @@ def sample_coord(reg): return value return fp_operand(reg, scalar, vector, pending, sample_dest) - if op in ("image_sample_lz", "image_sample_l"): + if base_op in ("image_sample_lz", "image_sample_l"): u, v = [sample_coord(reg) for reg in coord_regs[:2]] - lod = sample_coord(coord_regs[2]) if op == "image_sample_l" else "0.0f" - call = f"SampleLevel(samp, float2({u}, {v}), {lod})" + lod = sample_coord(coord_regs[2]) if base_op == "image_sample_l" else "0.0f" + call = f"SampleLevel(samp, float2({u}, {v}), {lod}{offset_arg})" else: # RDNA2 places bias before the UV pair. Only UV contributes derivatives. uv = [vector[reg] for reg in coord_regs[-2:]] if any(value not in quad_values for value in uv): raise ValueError("Unsupported texture coordinate") coordinate = f"float2({', '.join(uv)})" - if op == "image_sample_b": + if base_op == "image_sample_b": bias = sample_coord(coord_regs[0]) - call = f"SampleBias(samp, {coordinate}, {bias})" + call = f"SampleBias(samp, {coordinate}, {bias}{offset_arg})" else: - call = f"Sample(samp, {coordinate})" + call = f"Sample(samp, {coordinate}{offset_arg})" lines.append(f" float4 sample{i} = {texture}.{call};") samples += 1 vector_loads += 1 @@ -5641,6 +5663,8 @@ def main(): parser.add_argument("record") parser.add_argument("--container-sha256", help="SHA-256 of the full decoded DXBC container to select by name") parser.add_argument("--llvm", required=True, help="LLVM C library with AMDGPU support") + parser.add_argument("--cpu", choices=("gfx1013", "gfx1030"), default="gfx1013", + help="Source instruction set (gfx1030 uses the wave64 pixel profile)") parser.add_argument("--texture-sgpr", type=int, required=True, help="Entry register for the low descriptor-table address") parser.add_argument("--interp-sgpr", type=int, required=True, help="Entry register for the interpolation base") profile = parser.add_mutually_exclusive_group(required=True) @@ -5669,8 +5693,11 @@ def main(): if dest.suffix.lower() != ".hlsl" or dest == args.archive.resolve(): parser.error("Choose an HLSL destination distinct from the input") try: - blob, code = native_program(args.archive, args.record, container_sha256=args.container_sha256, llvm=args.llvm) - instructions = disassemble(code, args.llvm, offsets=True) + cpu = args.cpu.encode() + features = b"+wavefrontsize64,-wavefrontsize32" if cpu == b"gfx1030" else b"" + blob, code = native_program(args.archive, args.record, container_sha256=args.container_sha256, + llvm=args.llvm, cpu=cpu, features=features) + instructions = disassemble(code, args.llvm, offsets=True, cpu=cpu, features=features) if args.rt0_write_mask and any(line.startswith("exp ") and "compr" in line.split() for _, line in instructions): raise ValueError("--rt0-write-mask only supports uncompressed exports") From 12864bdb0067551b9b781e01fd50e877337c0502 Mon Sep 17 00:00:00 2001 From: denn0x <55638248+denn0x@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:40:38 +0000 Subject: [PATCH 046/775] startup: fail page-destination requests whose page array is unreadable at run time run_entry kept the token captured at EnqueueRequest for any page-array entry it could not read when the request ran. It now checks the whole array first and fails the request (E_FAIL) before any destination page is written; otherwise it copies the array once and uses that copy. startup_stub_consumer dstorage-pages (run by the startup_stubs test) covers a non-zero entry replaced between EnqueueRequest and Submit (the new page receives the data, the old page keeps its sentinel) and an array made no-access before Submit (that request fails, its pages keep their sentinel, and a valid request queued after it completes). AI-assisted (Claude Code). --- docs/startup-runtime.md | 5 +- src/startup_stubs/xcrdapi.cpp | 27 +++++-- tests/startup_stub_check.py | 8 ++ tests/startup_stub_consumer.cpp | 137 ++++++++++++++++++++++++++++++++ 4 files changed, 168 insertions(+), 9 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 7da04a718..bf8306579 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -268,7 +268,10 @@ These are measured on one executable; treat them as hypotheses for others. - **DirectStorage ordering.** Requests must run after `Submit`, in order with status and fence entries. Titles fill destination page-array entries after `EnqueueRequest`, and also replace entries filled earlier, so the whole page array is read again when the request runs. The - heartbeat counts entries replaced after enqueue. + heartbeat counts entries replaced after enqueue. The caller must keep the page array readable, + and stop changing it, once the request is submitted: the worker copies it once when the request + runs. If the array cannot be read then, the request fails before any destination page is + written; a token captured at enqueue is never used. - **Sub-dword addressing (SDWA).** The translator lowers the byte and word selects of the 32-bit integer VOP1/VOP2 SDWA forms: a source selection is zero-extended, or sign-extended under `sext()`, and the low bits of the result are placed in the destination field, with `UNUSED_PAD` zeroing the diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 9c139ae9b..716d9e810 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -570,14 +570,25 @@ void run_entry(Object* self, Entry& entry) const auto* title = *reinterpret_cast(entry.bytes + 0x08); // The title's page array is read again in full when the request runs: entries are filled, // and also replaced, after enqueue. Writing through a token captured at enqueue put data - // into a page the title had already reassigned. - for (std::size_t i = 0; i < entry.tokens.size(); ++i) - if (title && x2w_local::readable(title + i, sizeof(ULONG_PTR))) { - const ULONG_PTR now = title[i]; - if (entry.tokens[i] && now != entry.tokens[i]) InterlockedIncrement(&tokens_replaced_after_enqueue); - entry.tokens[i] = now; - if (!entry.tokens[i]) InterlockedIncrement(&zero_tokens_at_run); - } + // into a page the title had already reassigned. The caller has to keep the array readable + // until the request runs; if it is not, the request fails before any page is written, so + // no token captured at enqueue is ever used. + const std::size_t bytes = entry.tokens.size() * sizeof(ULONG_PTR); + if (!title || !x2w_local::readable(title, bytes)) { + InterlockedIncrement(&requests_failed); + if (self) InterlockedExchange(&self->pending, static_cast(E_FAIL)); + static LONG unreadable; + if (InterlockedIncrement(&unreadable) <= 12) + log("x2w-dstorage options=0x%llx page array %p (%zu entries) unreadable when the request runs -> failed", options, + static_cast(title), entry.tokens.size()); + return; + } + std::vector now(title, title + entry.tokens.size()); // one snapshot of the whole array + for (std::size_t i = 0; i < now.size(); ++i) { + if (entry.tokens[i] && now[i] != entry.tokens[i]) InterlockedIncrement(&tokens_replaced_after_enqueue); + if (!now[i]) InterlockedIncrement(&zero_tokens_at_run); + } + entry.tokens = std::move(now); } execute_request(self, entry.bytes, entry.tokens.empty() ? nullptr : entry.tokens.data(), entry.id, entry.submission_id); } else if (entry.type == Entry::status_entry) { diff --git a/tests/startup_stub_check.py b/tests/startup_stub_check.py index 4e63b2df5..3fbdf5967 100644 --- a/tests/startup_stub_check.py +++ b/tests/startup_stub_check.py @@ -98,6 +98,14 @@ if not ok: failures.append(f"dstorage control: exit {run.returncode}, stderr {run.stderr.strip()!r}") +# Page arrays changed between EnqueueRequest and Submit: a replaced entry, and an unreadable array. +run = subprocess.run([consumer, "dstorage-pages"], capture_output=True, text=True, env=env, timeout=20) +print(run.stdout.strip()) +ok = run.returncode == 0 and "dstorage-pages ok" in run.stdout and "x2w-trap" not in run.stderr +print(f"dstorage page-array control: exit={run.returncode} {'ok' if ok else 'MISMATCH'}") +if not ok: + failures.append(f"dstorage page-array control: exit {run.returncode}, stdout {run.stdout.strip()!r}") + if failures: print("FAIL") for f in failures: diff --git a/tests/startup_stub_consumer.cpp b/tests/startup_stub_consumer.cpp index 49e7ceda4..6e7579f52 100644 --- a/tests/startup_stub_consumer.cpp +++ b/tests/startup_stub_consumer.cpp @@ -6,6 +6,7 @@ // xg_xs -> XGSuggestSwizzleMode(0x55, 0, 0, 0) // physical -> XMemAllocatePhysicalPages/XMemFreePhysicalPages round trip (no trap expected) // dstorage -> DirectStorage multi-page RFC 1950 zlib request, BCPack decode and failure controls (Refs #1139, #1144) +// dstorage-pages -> page-array entries replaced, or made unreadable, between EnqueueRequest and Submit #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -171,6 +172,137 @@ long __stdcall hold_worker(void* fence, u64) { return S_OK; } +// Page-destination requests whose page array changes between EnqueueRequest and Submit: +// replaced: a non-zero entry is replaced; the new page receives the data and the old page keeps +// its sentinel. +// unreadable: the array becomes unreadable; that request fails without writing any page, and a +// valid request queued after it on the same queue still completes. +// Prints one line per case; returns false on the first mismatch. +bool dstorage_page_array_checks() { + _putenv("X2W_XMEM_PERMISSIVE=1"); + HMODULE xcrdapi = LoadLibraryA("XCRDAPI.dll"); + if (!xcrdapi) return false; + auto get_factory = reinterpret_cast(GetProcAddress(xcrdapi, "DStorageGetFactory")); + void* factory_ptr = nullptr; + if (!get_factory || get_factory(nullptr, &factory_ptr) != 0 || !factory_ptr) return false; + auto* factory = static_cast(factory_ptr); + + const size_t page = 64 * 1024; + std::vector plain(2 * page); + for (size_t i = 0; i < plain.size(); ++i) plain[i] = static_cast((i % 251) ^ 0x5a); + const auto two_pages = make_stored_zlib(plain.data(), plain.size()); + const auto one_page = make_stored_zlib(plain.data(), page); + + size_t page_count = 3; + u64 pages[3] = {}; + if (!XMemAllocatePhysicalPages(0x20400000ull, &page_count, pages) || page_count != 3) return false; + // Each physical page gets its own view, so every page can be checked after a request. + void* view[3] = {}; + for (int i = 0; i < 3; ++i) { + const ULONG_PTR token = pages[i]; + view[i] = XMemVirtualAlloc(nullptr, page, 0x20402000, 0x21, PAGE_READWRITE); + if (!view[i] || XMemMapPhysicalPages(view[i], 1, &token) != view[i]) return false; + } + auto fill = [&](unsigned char value) { + for (void* v : view) std::memset(v, value, page); + }; + auto untouched = [&](int i, unsigned char value) { + const auto* bytes = static_cast(view[i]); + for (size_t k = 0; k < page; ++k) + if (bytes[k] != value) return false; + return true; + }; + auto request_for = [](unsigned char* request, const ULONG_PTR* tokens, unsigned size, const std::vector& data, + unsigned decoded) { + std::memset(request, 0, 0x48); + *reinterpret_cast(request + 0x00) = 1 | (1ull << 21) | 0x400000; // zlib, page destination, memory source + *reinterpret_cast(request + 0x08) = tokens; + *reinterpret_cast(request + 0x18) = size; + *reinterpret_cast(request + 0x20) = data.data(); + *reinterpret_cast(request + 0x30) = static_cast(data.size()); + *reinterpret_cast(request + 0x38) = decoded; + }; + auto make_queue = [&](unsigned statuses, Object** queue, Object** status) { + void* status_ptr = nullptr; + void* queue_ptr = nullptr; + unsigned char desc[0x20] = {}; + *reinterpret_cast(desc + 8) = 16; + if (reinterpret_cast(factory->vtable[5])(factory, statuses, "Status", nullptr, &status_ptr) != 0 || + !status_ptr || reinterpret_cast(factory->vtable[10])(factory, desc, nullptr, &queue_ptr) != 0 || !queue_ptr) + return false; + *queue = static_cast(queue_ptr); + *status = static_cast(status_ptr); + return true; + }; + auto result_of = [](Object* status, unsigned index, long* hr) { + for (int i = 0; i < 200 && !reinterpret_cast(status->vtable[3])(status, index); ++i) Sleep(10); + if (!reinterpret_cast(status->vtable[3])(status, index)) return false; + *hr = reinterpret_cast(status->vtable[4])(status, index); + return true; + }; + + // replaced: enqueue with {page 0, page 1}, then replace entry 1 with page 2 before Submit. + { + Object *queue = nullptr, *status = nullptr; + if (!make_queue(1, &queue, &status)) return false; + fill(0xAA); + ULONG_PTR tokens[2] = {pages[0], pages[1]}; + unsigned char request[0x48]; + request_for(request, tokens, static_cast(2 * page), two_pages, static_cast(2 * page)); + reinterpret_cast(queue->vtable[3])(queue, request); + reinterpret_cast(queue->vtable[4])(queue, status, 0); + tokens[1] = pages[2]; + reinterpret_cast(queue->vtable[6])(queue); + long hr = -1; + const bool done = result_of(status, 0, &hr); + const bool first = done && std::memcmp(view[0], plain.data(), page) == 0; + const bool moved = done && std::memcmp(view[2], plain.data() + page, page) == 0; + const bool old_kept = done && untouched(1, 0xAA); + std::printf("replaced: hr=0x%08lx first page %s, new page %s, old page %s\n", static_cast(hr), + first ? "ok" : "WRONG", moved ? "ok" : "WRONG", old_kept ? "kept" : "WRITTEN"); + if (!done || hr != 0 || !first || !moved || !old_kept) return false; + } + + // unreadable: the first request's array is made no-access before Submit; a valid one follows. + { + Object *queue = nullptr, *status = nullptr; + if (!make_queue(2, &queue, &status)) return false; + fill(0xAA); + auto* tokens = static_cast(VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!tokens) return false; + tokens[0] = pages[0]; + tokens[1] = pages[1]; + unsigned char bad[0x48]; + request_for(bad, tokens, static_cast(2 * page), two_pages, static_cast(2 * page)); + const ULONG_PTR good_tokens[1] = {pages[2]}; + unsigned char good[0x48]; + request_for(good, good_tokens, static_cast(page), one_page, static_cast(page)); + reinterpret_cast(queue->vtable[3])(queue, bad); + reinterpret_cast(queue->vtable[4])(queue, status, 0); + reinterpret_cast(queue->vtable[3])(queue, good); + reinterpret_cast(queue->vtable[4])(queue, status, 1); + DWORD old_protection = 0; + if (!VirtualProtect(tokens, 4096, PAGE_NOACCESS, &old_protection)) return false; + reinterpret_cast(queue->vtable[6])(queue); + long bad_hr = 0, good_hr = -1; + const bool done = result_of(status, 0, &bad_hr) && result_of(status, 1, &good_hr); + const bool kept = done && untouched(0, 0xAA) && untouched(1, 0xAA); + const bool good_written = done && std::memcmp(view[2], plain.data(), page) == 0; + std::printf("unreadable: failed request hr=0x%08lx, pages %s; following request hr=0x%08lx, page %s\n", + static_cast(bad_hr), kept ? "kept" : "WRITTEN", static_cast(good_hr), + good_written ? "ok" : "WRONG"); + VirtualFree(tokens, 0, MEM_RELEASE); + if (!done || bad_hr == 0 || !kept || good_hr != 0 || !good_written) return false; + } + + for (void* v : view) { + XMemMapPhysicalPages(v, 1, nullptr); + VirtualFree(v, 0, MEM_RELEASE); + } + XMemFreePhysicalPages(3, pages); + return true; +} + bool dstorage_checks() { _putenv("X2W_XMEM_PERMISSIVE=1"); @@ -1488,6 +1620,11 @@ int main(int argc, char** argv) return 0; } if (!std::strcmp(which, "dstorage-directory")) return dstorage_directory_batches() ? 0 : 8; + if (!std::strcmp(which, "dstorage-pages")) { + if (!dstorage_page_array_checks()) return 9; + std::puts("dstorage-pages ok"); + return 0; + } if (!std::strcmp(which, "dstorage")) { if (!dstorage_checks()) return 7; std::puts("dstorage ok"); From e8003928576871c5fa7dd0de55a49296aa0c6e55 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 19:40:47 +0800 Subject: [PATCH 047/775] Hold 1 ms timer resolution while the desktop audio connection is active --- CMakeLists.txt | 1 + docs/startup-runtime.md | 5 +++++ src/startup_stubs/xapu.cpp | 24 +++++++++++++++++++++++- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6afbef55b..428fe24c6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -295,6 +295,7 @@ endforeach() # link the shims statically so they never use its runtime (constexpr std::mutex layout). target_link_libraries(startup_stub_xg_xs PRIVATE d3d12 dxguid) target_link_libraries(startup_stub_gameinput PRIVATE user32) +target_link_libraries(startup_stub_xapu PRIVATE winmm) # The DirectStorage heartbeat reports this process's peak commit (#1199). target_link_libraries(startup_stub_xcrdapi PRIVATE psapi) target_sources(startup_stub_gameinput PRIVATE src/startup_stubs/runtime_proxy.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 75ef1d4b9..c9a3866a2 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -458,6 +458,11 @@ These are measured on one executable; treat them as hypotheses for others. ## Audio output +While a permissive XApu connection is open, the desktop shim requests 1 ms Windows +timer resolution for the mix worker's short refill waits. The last disconnect +releases the request. This affects scheduling and preserves the existing audio +routing and sample format. + `src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only), converts each submitted block (format, frame count, bytes) to it, and writes it through diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index e56e4c4af..f357ae27b 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -4,6 +4,7 @@ #define X2W_TRAP_MODULE_ID 3 #include "startup_stubs/trap.h" #include "startup_stubs/local_log.h" +#include // Experimental (docs/startup-runtime.md). With X2W_AUDIO_PERMISSIVE=1 the exports // stand in for the audio command queue; otherwise they trap. Call shapes from the title: @@ -18,6 +19,9 @@ namespace { using u64 = std::uint64_t; bool permissive() noexcept { return x2w_local::env_on("X2W_AUDIO_PERMISSIVE"); } int connection; // its address is the handle +SRWLOCK connection_lock = SRWLOCK_INIT; +unsigned long long connection_count = 0; +bool timer_active = false; void hex(const void* data, std::size_t bytes, char* out, std::size_t size) { @@ -36,7 +40,17 @@ extern "C" __declspec(noinline) long XApuConnect(u64 rcx, u64 rdx, u64 r8, u64 r char input[3 * 0x18 + 1], output[3 * 0x10 + 1]; hex(reinterpret_cast(rcx), 0x18, input, sizeof(input)); hex(reinterpret_cast(rdx), 0x10, output, sizeof(output)); - if (r8) *reinterpret_cast(r8) = &connection; + if (r8) { + *reinterpret_cast(r8) = &connection; + AcquireSRWLockExclusive(&connection_lock); + if (connection_count++ == 0) { + // The mix worker sleeps for 2 ms between refills. A coarse Windows tick can + // stretch that wait beyond the time represented by the queued samples. + timer_active = timeBeginPeriod(1) == TIMERR_NOERROR; + if (!timer_active) x2w_local::logf("x2w-audio 1 ms mixer timer request unavailable"); + } + ReleaseSRWLockExclusive(&connection_lock); + } x2w_local::logf("x2w-audio XApuConnect input=[%s] output(before)=[%s] -> handle %p, S_OK", input, output, static_cast(&connection)); return r8 ? 0 : static_cast(0x80004003); @@ -80,5 +94,13 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuDisconnect", 2, rcx, rdx, r8, r9, _ReturnAddress()); x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx", rcx); + if (rcx == reinterpret_cast(&connection)) { + AcquireSRWLockExclusive(&connection_lock); + if (connection_count && --connection_count == 0 && timer_active) { + timeEndPeriod(1); + timer_active = false; + } + ReleaseSRWLockExclusive(&connection_lock); + } return 0; } From eba22f70725198c629c8f41550aaa313a74d7c8d Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:41:36 +0100 Subject: [PATCH 048/775] docs: document R24G8 and added MSAA colour console plane sizing and its verification status --- docs/startup-runtime.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 75ef1d4b9..dd69e7470 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -606,6 +606,19 @@ The rule covers a 2D texture with exactly one mip, dimensions within the D3D12 l description keeps the desktop answer. A desktop failure is kept for desktop formats; only the console-only formats 118-120, which desktop cannot answer, are answered over it. +Covered formats: depth with stencil in the R32G8X24 family (formats 19-22), the R24G8 family +(44-47, a 4-byte depth plane plus a 1-byte stencil plane) and the console 16-bit depth with +stencil (118-120); multisampled colour in the R32G32B32A32 (1-4), R16G16B16A16 (9-14), R10G10B10A2, +R11G11B10 and R8G8B8A8 (23-32), R16G16 (33-38), R32 (39-43), R16 (53-59), R8 and A8 (60-65) and +B8G8R8A8/B8G8R8X8 (87-93) families. Both allocation-info entries (slots 25 and 108) give the same +answer for them. + +Verification status: the device-independent reference sizes in `tests/startup_plane_size_check.cpp` +(`startup_plane_size`) cover R24G8 and the added colour families. The R24G8 and added MSAA colour +formats have not yet been verified through the Windows device wrapper +(`startup_plane_size_device_`, reproduced with the second command below); only the fixture result +is established for them. + - `ctest --preset release --no-tests=error -R '^startup_plane_size(_packed_control)?$' -V` checks the rule without a device, including the shapes it refuses. - `ctest --preset release --no-tests=error -R '^startup_plane_size_device_' -V` goes through the From 99624a8dbaa50f737fe6aacb461485b331011678 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:16:37 +0100 Subject: [PATCH 049/775] fix: view typeless presented surfaces through a typed format --- CMakeLists.txt | 15 ++ docs/experiments.md | 11 + docs/startup-runtime.md | 11 + src/startup_stubs/d3d12_present.inl | 8 +- src/startup_stubs/d3d12_xs_device.cpp | 1 + src/startup_stubs/present_view_format.h | 45 +++++ tests/startup_present_view_check.cpp | 257 ++++++++++++++++++++++++ 7 files changed, 347 insertions(+), 1 deletion(-) create mode 100644 src/startup_stubs/present_view_format.h create mode 100644 tests/startup_present_view_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index bcf07826a..918660895 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -634,6 +634,21 @@ add_executable(startup_memory_srv_report_check tests/startup_memory_srv_report_c target_include_directories(startup_memory_srv_report_check PRIVATE src) target_compile_features(startup_memory_srv_report_check PRIVATE cxx_std_17) add_test(NAME startup_memory_srv_report COMMAND startup_memory_srv_report_check) + +# View format of the window presenter's read of typeless textures (src/startup_stubs/present_view_format.h); +# the identity run is the old behaviour and the sRGB run is a wrong view; both are negative controls. +add_executable(startup_present_view_check tests/startup_present_view_check.cpp) +target_include_directories(startup_present_view_check PRIVATE src) +target_compile_features(startup_present_view_check PRIVATE cxx_std_17) +target_link_libraries(startup_present_view_check PRIVATE d3d12 dxgi d3dcompiler) +add_test(NAME startup_present_view COMMAND startup_present_view_check) +add_test(NAME startup_present_view_identity_control COMMAND startup_present_view_check --mutate identity) +foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_present_view_${adapter} COMMAND startup_present_view_check ${adapter}) +endforeach() +add_test(NAME startup_present_view_srgb_control COMMAND startup_present_view_check warp --mutate srgb) +set_tests_properties(startup_present_view_identity_control startup_present_view_srgb_control PROPERTIES WILL_FAIL TRUE) +set_tests_properties(startup_present_view_hardware PROPERTIES SKIP_RETURN_CODE 77) # Console allocation sizes for depth-with-stencil and multisampled textures # (src/startup_stubs/console_plane_size.h); the mutated run is the negative control. add_executable(startup_plane_size_check tests/startup_plane_size_check.cpp) diff --git a/docs/experiments.md b/docs/experiments.md index 3d587f5ba..a098b6c6e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15,6 +15,17 @@ that operand loses three patterns under optimized FXC. ctest --preset dev --no-tests=error -R '^startup_mrt_' -V ``` +## Typeless surfaces in the window presenter + +A presented texture in an 8-bit RGBA/BGRA/BGRX or 10:10:10:2 `_TYPELESS` format is sampled through its UNORM +view; other typeless formats are refused, not guessed. `startup_present_view_check` compares a compute +readback of 16 texels per family on WARP and hardware with a CPU decode of the uploaded bytes. The identity +mapping (the old behaviour) fails the table; an sRGB view of the RGBA8 texture fails on the first texel (0x03 reads 0.0009, not 0.0118). + +```powershell +ctest --preset dev --no-tests=error -R '^startup_present_view' -V +``` + ## CPU-written R8 planes across frames The startup draw uploader checks a single-mip, single-slice R8_UNORM texture of up to 32 MiB diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 75ef1d4b9..a078570b6 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -38,6 +38,17 @@ requested view. This applies only to Texture2D views with no resource or counter `ctest --test-dir out/bin --no-tests=error -R "^startup_null_views_" -V` against your build directory to exercise both slots on hardware and WARP. +## Typeless presented surfaces + +The window presenter reads the presented surface through a shader resource view, which needs a +typed format. A surface created as R8G8B8A8, B8G8R8A8, B8G8R8X8 or R10G10B10A2 `_TYPELESS` is viewed +as the UNORM member of its family (`src/startup_stubs/present_view_format.h`); no sRGB conversion +is added. Any other typeless format (16 or 32 bits a channel, depth/stencil planes, block-compressed) +is ambiguous: the surface is not shown and the first four are logged. Typed formats pass unchanged. +Build `startup_present_view_check` and run +`ctest --preset dev --no-tests=error -R '^startup_present_view' -V`; the identity and sRGB runs are +negative controls and must fail. + ## 16-bit packed targets A description that asks for a B5G5R5A1_UNORM or B4G4R4A4_UNORM render target is created as diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 59582234c..8eb6afd3e 100644 --- a/src/startup_stubs/d3d12_present.inl +++ b/src/startup_stubs/d3d12_present.inl @@ -172,8 +172,14 @@ bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) const D3D12_RESOURCE_DESC desc = surface->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1) return false; ID3D12Device* device = device_of(the_device); + const DXGI_FORMAT view_format = x2w_startup::present_view_format(desc.Format); + if (view_format == DXGI_FORMAT_UNKNOWN) { + static LONG refused; + if (first_calls(refused, 4)) log("x2w-present surface format %d has no single typed view; not shown (present_view_format.h)", desc.Format); + return false; + } D3D12_SHADER_RESOURCE_VIEW_DESC view{}; - view.Format = desc.Format; + view.Format = view_format; view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; view.Texture2D.MipLevels = 1; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 801e601c8..90f86ae7a 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -33,6 +33,7 @@ #include "null_binding_cause.h" #include "null_texture_view.h" #include "packed_target_format.h" +#include "present_view_format.h" #include "state_block_blend.h" #include "title_heap_memory.h" #include diff --git a/src/startup_stubs/present_view_format.h b/src/startup_stubs/present_view_format.h new file mode 100644 index 000000000..3dd26e515 --- /dev/null +++ b/src/startup_stubs/present_view_format.h @@ -0,0 +1,45 @@ +// Experimental (docs/startup-runtime.md): the format of the view the window presenter samples. +// +// The presenter draws the presented surface with a shader that reads a float4. A texture created +// with a typeless format cannot be viewed with that format: a shader resource view needs a typed +// one. The 8-bit and 10:10:10:2 colour families are viewed as UNORM, the only member that a float4 +// read takes unchanged; no sRGB conversion is added, because that is a colour choice. A typeless +// format that names several readings (16 and 32 bits a channel: float, unorm, snorm, uint, sint; +// depth/stencil planes; block-compressed data) is refused instead of guessed. A typed format +// passes unchanged. DXGI_FORMAT_UNKNOWN means refused. +#pragma once + +#include + +namespace x2w_startup { +inline DXGI_FORMAT present_view_format(DXGI_FORMAT format) +{ + constexpr unsigned last_format = 132; // DXGI_FORMAT_V408; larger values are not formats a surface has + switch (format) { + case DXGI_FORMAT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_UNORM; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM; + case DXGI_FORMAT_B8G8R8X8_TYPELESS: return DXGI_FORMAT_B8G8R8X8_UNORM; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: return DXGI_FORMAT_R10G10B10A2_UNORM; + case DXGI_FORMAT_R32G32B32A32_TYPELESS: + case DXGI_FORMAT_R32G32B32_TYPELESS: + case DXGI_FORMAT_R16G16B16A16_TYPELESS: + case DXGI_FORMAT_R32G32_TYPELESS: + case DXGI_FORMAT_R32G8X24_TYPELESS: + case DXGI_FORMAT_R16G16_TYPELESS: + case DXGI_FORMAT_R32_TYPELESS: + case DXGI_FORMAT_R24G8_TYPELESS: + case DXGI_FORMAT_R8G8_TYPELESS: + case DXGI_FORMAT_R16_TYPELESS: + case DXGI_FORMAT_R8_TYPELESS: + case DXGI_FORMAT_BC1_TYPELESS: + case DXGI_FORMAT_BC2_TYPELESS: + case DXGI_FORMAT_BC3_TYPELESS: + case DXGI_FORMAT_BC4_TYPELESS: + case DXGI_FORMAT_BC5_TYPELESS: + case DXGI_FORMAT_BC6H_TYPELESS: + case DXGI_FORMAT_BC7_TYPELESS: + case DXGI_FORMAT_UNKNOWN: return DXGI_FORMAT_UNKNOWN; + default: return static_cast(format) <= last_format ? format : DXGI_FORMAT_UNKNOWN; + } +} +} // namespace x2w_startup diff --git a/tests/startup_present_view_check.cpp b/tests/startup_present_view_check.cpp new file mode 100644 index 000000000..b4cd86632 --- /dev/null +++ b/tests/startup_present_view_check.cpp @@ -0,0 +1,257 @@ +// Checks src/startup_stubs/present_view_format.h. No argument: the format table, without a device. +// "warp" or "hardware": the presenter's read of typeless textures, as a compute readback of the +// texels through the mapped view against a CPU decode of the bytes that were uploaded. +// --mutate identity: the table with the old behaviour (the typeless format unchanged); it must fail. +// --mutate srgb: the device run with an sRGB view of the RGBA8 texture; it must fail on a texel. +#include "startup_stubs/present_view_format.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { +int failures; +bool identity, srgb; + +DXGI_FORMAT map_format(DXGI_FORMAT format) { return identity ? format : x2w_startup::present_view_format(format); } + +void expect(const char* name, DXGI_FORMAT format, DXGI_FORMAT wanted) +{ + if (map_format(format) != wanted) { + std::printf("FAIL %s: format %d -> %d, expected %d\n", name, format, map_format(format), wanted); + ++failures; + } +} + +void table() +{ + constexpr DXGI_FORMAT none = DXGI_FORMAT_UNKNOWN; + expect("rgba8", DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM); + expect("bgra8", DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM); + expect("bgrx8", DXGI_FORMAT_B8G8R8X8_TYPELESS, DXGI_FORMAT_B8G8R8X8_UNORM); + expect("rgb10a2", DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM); + for (DXGI_FORMAT typed : {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, + DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_BC1_UNORM}) + expect("typed passes", typed, typed); + for (DXGI_FORMAT ambiguous : {DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R16G16B16A16_TYPELESS, + DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R16G16_TYPELESS, + DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R8G8_TYPELESS, + DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC2_TYPELESS, + DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC6H_TYPELESS, + DXGI_FORMAT_BC7_TYPELESS}) + expect("ambiguous refused", ambiguous, none); + expect("unknown refused", DXGI_FORMAT_UNKNOWN, none); + expect("out of range refused", static_cast(0x7fff), none); +} + +void check(HRESULT hr, const char* what) +{ + if (FAILED(hr)) throw std::runtime_error(std::string(what) + " failed"); +} + +struct Case { + const char* name; + DXGI_FORMAT typeless; + DXGI_FORMAT view; + std::vector texel; // 16 texels, 4 bytes each, little-endian + float (*decode)(unsigned, int); +}; + +float decode_rgba8(unsigned t, int c) { return static_cast((t >> (8 * c)) & 255) / 255.0f; } +float decode_bgra8(unsigned t, int c) { return decode_rgba8(t, c == 0 ? 2 : c == 2 ? 0 : c); } +float decode_rgb10a2(unsigned t, int c) { return c == 3 ? static_cast(t >> 30) / 3.0f : static_cast((t >> (10 * c)) & 1023) / 1023.0f; } + +bool readback(ID3D12Device* device, const Case& item) +{ + constexpr UINT side = 4, pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT, out_bytes = side * side * 16; + const auto heap = [](D3D12_HEAP_TYPE type) { D3D12_HEAP_PROPERTIES p{}; p.Type = type; return p; }; + D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 0, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + const auto make_buffer = [&](D3D12_HEAP_TYPE type, UINT64 bytes, D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) { + ComPtr r; + buffer.Width = bytes; + buffer.Flags = flags; + const D3D12_HEAP_PROPERTIES properties = heap(type); + check(device->CreateCommittedResource(&properties, D3D12_HEAP_FLAG_NONE, &buffer, state, nullptr, IID_PPV_ARGS(&r)), "buffer"); + return r; + }; + auto upload = make_buffer(D3D12_HEAP_TYPE_UPLOAD, pitch * side, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + auto out = make_buffer(D3D12_HEAP_TYPE_DEFAULT, out_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + auto back = make_buffer(D3D12_HEAP_TYPE_READBACK, out_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + unsigned char* mapped = nullptr; + check(upload->Map(0, nullptr, reinterpret_cast(&mapped)), "map upload"); + for (UINT y = 0; y < side; ++y) std::memcpy(mapped + y * pitch, &item.texel[y * side], side * 4); + upload->Unmap(0, nullptr); + + D3D12_RESOURCE_DESC tex{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, item.typeless, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + ComPtr texture; + const D3D12_HEAP_PROPERTIES defaults = heap(D3D12_HEAP_TYPE_DEFAULT); + check(device->CreateCommittedResource(&defaults, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&texture)), "texture"); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ComPtr heaps; + check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heaps)), "heap"); + auto cpu = heaps->GetCPUDescriptorHandleForHeapStart(); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = srgb && item.view == DXGI_FORMAT_R8G8B8A8_UNORM ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : item.view; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + device->CreateShaderResourceView(texture.Get(), &srv, cpu); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R32_TYPELESS; + uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uav.Buffer.NumElements = out_bytes / 4; + uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + cpu.ptr += device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + device->CreateUnorderedAccessView(out.Get(), nullptr, &uav, cpu); + + static const char source[] = + "Texture2D src : register(t0); RWByteAddressBuffer dst : register(u0);\n" + "[numthreads(4, 4, 1)] void main(uint3 id : SV_DispatchThreadID)\n" + "{ dst.Store4((id.y * 4 + id.x) * 16, asuint(src.Load(int3(id.xy, 0)))); }\n"; + ComPtr code, signature, errors; + check(D3DCompile(source, sizeof(source) - 1, "view", nullptr, nullptr, "main", "cs_5_0", 0, 0, &code, &errors), "compile"); + const D3D12_DESCRIPTOR_RANGE ranges[2] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}, {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 1}}; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {2, ranges}; + const D3D12_ROOT_SIGNATURE_DESC root_desc{1, ¶meter, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &errors), "serialize"); + ComPtr root; + check(device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&root)), "root"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pipe{}; + pipe.pRootSignature = root.Get(); + pipe.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + ComPtr pipeline; + check(device->CreateComputePipelineState(&pipe, IID_PPV_ARGS(&pipeline)), "pipeline"); + + ComPtr queue; + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "queue"); + ComPtr allocator; + ComPtr list; + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), pipeline.Get(), IID_PPV_ARGS(&list)), "list"); + D3D12_TEXTURE_COPY_LOCATION to{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + D3D12_TEXTURE_COPY_LOCATION from{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + from.PlacedFootprint.Footprint = {item.typeless, side, side, 1, pitch}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + const auto transition = [&](ID3D12Resource* r, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Transition = {r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &b); + }; + transition(texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + ID3D12DescriptorHeap* bound[] = {heaps.Get()}; + list->SetDescriptorHeaps(1, bound); + list->SetComputeRootSignature(root.Get()); + list->SetComputeRootDescriptorTable(0, heaps->GetGPUDescriptorHandleForHeapStart()); + list->Dispatch(1, 1, 1); + transition(out.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(back.Get(), 0, out.Get(), 0, out_bytes); + check(list->Close(), "close"); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + ComPtr fence; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + check(queue->Signal(fence.Get(), 1), "signal"); + check(fence->SetEventOnCompletion(1, done), "event"); + WaitForSingleObject(done, 10000); + CloseHandle(done); + if (fence->GetCompletedValue() < 1) throw std::runtime_error("readback timed out"); + + const float* words = nullptr; + check(back->Map(0, nullptr, reinterpret_cast(const_cast(&words))), "map readback"); + int bad = 0; + for (int i = 0; i < 16 && bad < 3; ++i) + for (int c = 0; c < 4; ++c) { + const float expected = item.decode(item.texel[i], c); + if (std::fabs(words[i * 4 + c] - expected) > 1e-4f) { + std::printf("FAIL %s texel %d channel %d: read %f, expected %f\n", item.name, i, c, words[i * 4 + c], expected); + ++bad; + break; + } + } + back->Unmap(0, nullptr); + return bad == 0; +} + +ComPtr create_device(bool warp) +{ + ComPtr factory; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "factory"); + ComPtr adapter; + if (warp) { + check(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)), "warp adapter"); + } else { + for (UINT i = 0; factory->EnumAdapters(i, &adapter) == S_OK; ++i) { + DXGI_ADAPTER_DESC desc{}; + adapter->GetDesc(&desc); + if (desc.VendorId != 0x1414) break; // not the software adapter + adapter.Reset(); + } + } + ComPtr device; + if (adapter && SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) return device; + return nullptr; +} +} // namespace + +int main(int argc, char** argv) +{ + const char* adapter = nullptr; + for (int i = 1; i < argc; ++i) { + if (!std::strcmp(argv[i], "--mutate") && i + 1 < argc) { + ++i; + identity = !std::strcmp(argv[i], "identity"); + srgb = !std::strcmp(argv[i], "srgb"); + } else { + adapter = argv[i]; + } + } + if (!adapter) { + table(); + if (failures) { + std::printf("startup_present_view: %d FAILED\n", failures); + return 1; + } + std::printf("startup_present_view: PASS (4 mapped, 6 typed, 18 refused, 2 invalid)\n"); + return 0; + } + try { + auto device = create_device(!std::strcmp(adapter, "warp")); + if (!device) return std::strcmp(adapter, "warp") ? 77 : 1; + std::vector rgba(16), rgb10(16); + for (unsigned i = 0; i < 16; ++i) { + // Byte 0..3 are r, g, b, a for the RGBA family; a 128 value sits in each of the first channels. + rgba[i] = ((i * 16 + 3) | (255 - i * 16) << 8 | ((i * 37) & 255) << 16 | ((i * 53 + 7) & 255) << 24) & 0xffffffffu; + rgb10[i] = ((i * 61 + 5) & 1023) | ((i * 97 + 11) & 1023) << 10 | ((i * 131 + 17) & 1023) << 20 | (i & 3) << 30; + } + rgba[5] = 0x80808080u; + const Case cases[] = { + {"rgba8", DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, rgba, decode_rgba8}, + {"bgra8", DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM, rgba, decode_bgra8}, + {"rgb10a2", DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM, rgb10, decode_rgb10a2}, + }; + for (const Case& item : cases) { + Case run = item; + run.view = map_format(item.typeless); + if (!readback(device.Get(), run)) ++failures; + } + } catch (const std::exception& error) { + std::printf("startup_present_view: %s\n", error.what()); + return 1; + } + if (failures) return 1; + std::printf("startup_present_view_%s: PASS (3 families read back)\n", adapter); + return 0; +} From 4dc61c82df85d9c1e5ecc441a73a1cb531c9c7a8 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:16:48 +0100 Subject: [PATCH 050/775] docs: keep the presenter note in experiments.md only --- docs/startup-runtime.md | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a078570b6..75ef1d4b9 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -38,17 +38,6 @@ requested view. This applies only to Texture2D views with no resource or counter `ctest --test-dir out/bin --no-tests=error -R "^startup_null_views_" -V` against your build directory to exercise both slots on hardware and WARP. -## Typeless presented surfaces - -The window presenter reads the presented surface through a shader resource view, which needs a -typed format. A surface created as R8G8B8A8, B8G8R8A8, B8G8R8X8 or R10G10B10A2 `_TYPELESS` is viewed -as the UNORM member of its family (`src/startup_stubs/present_view_format.h`); no sRGB conversion -is added. Any other typeless format (16 or 32 bits a channel, depth/stencil planes, block-compressed) -is ambiguous: the surface is not shown and the first four are logged. Typed formats pass unchanged. -Build `startup_present_view_check` and run -`ctest --preset dev --no-tests=error -R '^startup_present_view' -V`; the identity and sRGB runs are -negative controls and must fail. - ## 16-bit packed targets A description that asks for a B5G5R5A1_UNORM or B4G4R4A4_UNORM render target is created as From 23a3533d9b021e6c703e4218bbfdbead4dd0873d Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:30:30 +0100 Subject: [PATCH 051/775] gpu/tests: preserve typed formats above V408 and reject NaN readbacks (#1425) --- src/startup_stubs/present_view_format.h | 3 +-- tests/startup_present_view_check.cpp | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/startup_stubs/present_view_format.h b/src/startup_stubs/present_view_format.h index 3dd26e515..17ef9b0e7 100644 --- a/src/startup_stubs/present_view_format.h +++ b/src/startup_stubs/present_view_format.h @@ -14,7 +14,6 @@ namespace x2w_startup { inline DXGI_FORMAT present_view_format(DXGI_FORMAT format) { - constexpr unsigned last_format = 132; // DXGI_FORMAT_V408; larger values are not formats a surface has switch (format) { case DXGI_FORMAT_R8G8B8A8_TYPELESS: return DXGI_FORMAT_R8G8B8A8_UNORM; case DXGI_FORMAT_B8G8R8A8_TYPELESS: return DXGI_FORMAT_B8G8R8A8_UNORM; @@ -39,7 +38,7 @@ inline DXGI_FORMAT present_view_format(DXGI_FORMAT format) case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_UNKNOWN: return DXGI_FORMAT_UNKNOWN; - default: return static_cast(format) <= last_format ? format : DXGI_FORMAT_UNKNOWN; + default: return format; } } } // namespace x2w_startup diff --git a/tests/startup_present_view_check.cpp b/tests/startup_present_view_check.cpp index b4cd86632..38f2f0996 100644 --- a/tests/startup_present_view_check.cpp +++ b/tests/startup_present_view_check.cpp @@ -39,7 +39,8 @@ void table() expect("bgrx8", DXGI_FORMAT_B8G8R8X8_TYPELESS, DXGI_FORMAT_B8G8R8X8_UNORM); expect("rgb10a2", DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM); for (DXGI_FORMAT typed : {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, - DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_BC1_UNORM}) + DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_BC1_UNORM, + static_cast(191) /* DXGI_FORMAT_A4B4G4R4_UNORM */}) expect("typed passes", typed, typed); for (DXGI_FORMAT ambiguous : {DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R16G16_TYPELESS, @@ -49,7 +50,6 @@ void table() DXGI_FORMAT_BC7_TYPELESS}) expect("ambiguous refused", ambiguous, none); expect("unknown refused", DXGI_FORMAT_UNKNOWN, none); - expect("out of range refused", static_cast(0x7fff), none); } void check(HRESULT hr, const char* what) @@ -175,7 +175,7 @@ bool readback(ID3D12Device* device, const Case& item) for (int i = 0; i < 16 && bad < 3; ++i) for (int c = 0; c < 4; ++c) { const float expected = item.decode(item.texel[i], c); - if (std::fabs(words[i * 4 + c] - expected) > 1e-4f) { + if (!(std::fabs(words[i * 4 + c] - expected) <= 1e-4f)) { std::printf("FAIL %s texel %d channel %d: read %f, expected %f\n", item.name, i, c, words[i * 4 + c], expected); ++bad; break; From d32b7feafb5224c4228740dae677e1d4ce4d676b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 14:43:09 +0300 Subject: [PATCH 052/775] startup: check that the last derived blend patch wins x2w_derived_blend::last_blend was reached only through the slot 55 draw in startup_stream_draw_{warp,hardware}. That draw kills a forward scan, a wrong or missing tag match and an off-by-one at either end, but it cannot see the descriptor offset the scan reports (only logged), and the device never hands it a null list or one that is not whole records. Mutants that report the tag's offset instead of the descriptor's, drop the whole-record check or drop the null check all pass that test. startup_derived_blend checks the header without a device: one and two blend patches, a blend patch before, between and after other parts, tags that only resemble 2, the returned offset and a byte-for-byte copy of the descriptor, and empty, null, short and prefixed lists. The first-wins control expects the earlier patch and must fail. --- CMakeLists.txt | 9 +++ docs/startup-runtime.md | 6 ++ tests/startup_derived_blend_check.cpp | 102 ++++++++++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 tests/startup_derived_blend_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 820ccc686..60882867e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -637,6 +637,15 @@ target_compile_features(startup_plane_size_check PRIVATE cxx_std_17) add_test(NAME startup_plane_size COMMAND startup_plane_size_check) add_test(NAME startup_plane_size_packed_control COMMAND startup_plane_size_check --mutate packed) set_tests_properties(startup_plane_size_packed_control PROPERTIES WILL_FAIL TRUE) +# The blend patch a slot 55 derivation applies (src/startup_stubs/derived_blend.h): the last part-2 +# record, its descriptor offset and bytes, and lists that are not whole records. The mutated run is +# the negative control. +add_executable(startup_derived_blend_check tests/startup_derived_blend_check.cpp) +target_include_directories(startup_derived_blend_check PRIVATE src) +target_compile_features(startup_derived_blend_check PRIVATE cxx_std_17) +add_test(NAME startup_derived_blend COMMAND startup_derived_blend_check) +add_test(NAME startup_derived_blend_first_wins_control COMMAND startup_derived_blend_check --mutate first-wins) +set_tests_properties(startup_derived_blend_first_wins_control PROPERTIES WILL_FAIL TRUE) # The same rule through the device wrapper: allocation-info slots 25 and 108, then a placed texture # (slot 133) over memory of the answered size. add_executable(startup_plane_size_device_check tests/startup_plane_size_device_check.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 75ef1d4b9..a74a88ac6 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -21,6 +21,12 @@ building `startup_stream_consumer`. The source-built shader writes to half of an On A8 the parent preserves the zero clear and the child writes alpha 255. R8 records red 0 or 255 according to the input shader. The untouched half stays zero in all four cases. +The patch scan itself also has a device-free check. Build `startup_derived_blend_check` and run +`ctest --preset dev --no-tests=error -R "^startup_derived_blend(_first_wins_control)?$" -V`. +It covers what the draw cannot observe: the logged descriptor offset (4 bytes into the record), +a byte-for-byte copy of the descriptor, and refusal of a null list or one that is not whole +records. The control expects the first blend patch to win and must fail. + ## Output window and fallback diagnostics The desktop swap chain has its own top-level window, class `X2WOutputWindow`. diff --git a/tests/startup_derived_blend_check.cpp b/tests/startup_derived_blend_check.cpp new file mode 100644 index 000000000..6755c7c8d --- /dev/null +++ b/tests/startup_derived_blend_check.cpp @@ -0,0 +1,102 @@ +// Checks src/startup_stubs/derived_blend.h without a device: which blend patch of a slot 55 patch +// list is found, the offset it is reported at, and the lists that have none. +#include "startup_stubs/derived_blend.h" + +#include +#include +#include +#include + +namespace { +using x2w_derived_blend::record_size; +int failures, cases; + +// A record whose 328 descriptor bytes count up from seed, so a copy that starts a word early or +// late, or comes from another record, differs in every byte. +void add(std::vector& list, std::uint32_t tag, unsigned char seed) +{ + const std::size_t at = list.size(); + list.resize(at + record_size); + std::memcpy(list.data() + at, &tag, sizeof(tag)); + for (std::size_t i = sizeof(tag); i < record_size; ++i) list[at + i] = static_cast(seed + i); +} + +void found(const char* name, const std::vector& list, std::size_t record) +{ + ++cases; + D3D12_BLEND_DESC blend; + std::memset(&blend, 0xee, sizeof(blend)); + std::size_t offset = ~std::size_t{0}; + const bool ok = x2w_derived_blend::last_blend(list.data(), list.size(), blend, offset); + const std::size_t expected = record * record_size + sizeof(std::uint32_t); + if (!ok || offset != expected || std::memcmp(&blend, list.data() + expected, sizeof(blend))) { + std::printf("FAIL %s: found %d at +0x%zx, expected record %zu at +0x%zx%s\n", name, ok, offset, record, expected, + ok && offset == expected ? " (descriptor bytes differ)" : ""); + ++failures; + } +} + +void none(const char* name, const unsigned char* records, std::size_t bytes) +{ + ++cases; + D3D12_BLEND_DESC blend{}; + std::size_t offset = 0; + if (x2w_derived_blend::last_blend(records, bytes, blend, offset)) { + std::printf("FAIL %s: found a blend patch at +0x%zx\n", name, offset); + std::fflush(stdout); // a scan that accepts a partial record may crash on a later case + ++failures; + } +} +} // namespace + +int main(int argc, char** argv) +{ + // --mutate first-wins: the expectations of a scan that keeps the first blend patch (a negative + // control: the check must then fail on the lists with two of them). + const bool first_wins = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "first-wins") == 0; + if (argc > 1 && !first_wins) { + std::printf("unknown mutation\n"); + return 2; + } + + std::vector list; + add(list, 2, 0x10); + found("one blend patch", list, 0); + add(list, 2, 0x80); + found("two blend patches", list, first_wins ? 0 : 1); + add(list, 3, 0x40); + add(list, 1, 0x50); + found("two blend patches, then parts 3 and 1", list, first_wins ? 0 : 1); + + list.clear(); + add(list, 2, 0x10); + add(list, 3, 0x20); + add(list, 0, 0x30); + found("blend patch first, then parts 3 and 0", list, 0); + list.clear(); + add(list, 3, 0x20); + add(list, 2, 0x10); + add(list, 0, 0x30); + found("blend patch between parts 3 and 0", list, 1); + + list.clear(); + for (std::uint32_t tag : {0u, 1u, 3u, 0x102u, 0x2000000u, 0xffffffffu}) add(list, tag, static_cast(tag)); + none("no part 2 (0, 1, 3, 0x102, 0x2000000, ~0)", list.data(), list.size()); + + // The size must be whole records: a 4-byte prefix before a whole blend patch is refused. + list.clear(); + list.resize(sizeof(std::uint32_t)); + add(list, 2, 0x10); + none("a blend patch after a 4-byte prefix", list.data(), list.size()); + none("a blend patch one byte short", list.data() + sizeof(std::uint32_t), record_size - 1); + none("no records", list.data(), 0); + none("null records, no bytes", nullptr, 0); + none("null records, one record of bytes", nullptr, record_size); + + if (failures) { + std::printf("startup_derived_blend: %d of %d FAILED\n", failures, cases); + return 1; + } + std::printf("startup_derived_blend: PASS (%d cases)\n", cases); + return 0; +} From 014f2c4714e3e824c42276371d5b99f25b813413 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:43:30 +0100 Subject: [PATCH 053/775] d3d12_xs: resolve DSVs from shadow records, refuse wrong-kind and mixed read-only views, keep DEPTH_READ when sampled, refuse DepthBoundsTestEnable; depth test emits adapter metadata and controls --- src/startup_stubs/d3d12_draw.inl | 7 ++- src/startup_stubs/d3d12_xs_device.cpp | 91 +++++++++++++++++++++++---- tests/startup_stream_depth.cpp | 48 +++++++++++--- tests/startup_stream_depth_check.py | 13 +++- 4 files changed, 134 insertions(+), 25 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 80fa117d8..7c75e1c6e 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -248,6 +248,11 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 } else if (type == 11 || type == 21) { // DEPTH_STENCIL (56B) / DEPTH_STENCIL1 (64B) std::memcpy(&depth_stencil, stream + at + sizeof(type), sizeof(depth_stencil)); has_depth_stencil = true; + if (type == 21) { // DEPTH_STENCIL1 appends DepthBoundsTestEnable; it has no translated equivalent + BOOL bounds = FALSE; + std::memcpy(&bounds, stream + at + sizeof(type) + sizeof(depth_stencil), sizeof(bounds)); + if (bounds) return nullptr; + } } else if (type == 16) { // DEPTH_STENCIL_FORMAT (8B) DXGI_FORMAT fmt = DXGI_FORMAT_UNKNOWN; std::memcpy(&fmt, stream + at + sizeof(type), sizeof(fmt)); @@ -915,7 +920,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } } if (texture) upload_texture(self, resource, texture); - if (texture) require_state(self, texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + if (texture) require_state(self, texture, sampled_state(self, texture)); const bool had_texture = texture != nullptr; bool mismatched = false; static LONG shown; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 197feaedc..b7651f9ce 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -991,22 +991,27 @@ bool render_mode() // Render-target view handle (desktop) -> the resource it views, recorded when the view is created. SRWLOCK target_lock = SRWLOCK_INIT; -std::unordered_map& view_targets() +struct ViewTarget { + ID3D12Resource* resource; + int slot; // 20 RTV, 21 DSV +}; +std::unordered_map& view_targets() { - static std::unordered_map map; + static std::unordered_map map; return map; } -void note_view_target(u64 handle, ID3D12Resource* resource) +void note_view_target(u64 handle, ID3D12Resource* resource, int slot) { AcquireSRWLockExclusive(&target_lock); - view_targets()[handle] = resource; + view_targets()[handle] = {resource, slot}; ReleaseSRWLockExclusive(&target_lock); } -ID3D12Resource* view_target(u64 handle) +// slot 0: either kind. A handle created as the other kind yields nothing. +ID3D12Resource* view_target(u64 handle, int slot = 0) { AcquireSRWLockShared(&target_lock); const auto found = view_targets().find(handle); - ID3D12Resource* resource = found == view_targets().end() ? nullptr : found->second; + ID3D12Resource* resource = found == view_targets().end() || (slot && found->second.slot != slot) ? nullptr : found->second.resource; ReleaseSRWLockShared(&target_lock); return resource; } @@ -1665,6 +1670,14 @@ void require_state(Wrapper* self, ID3D12Resource* resource, D3D12_RESOURCE_STATE transition(list, resource, D3D12_RESOURCE_STATE_COMMON, state); pass.states.emplace_back(resource, state); } +// State for a draw that samples `resource`: a depth texture also bound as a read-only DSV keeps DEPTH_READ. +D3D12_RESOURCE_STATES sampled_state(Wrapper* self, ID3D12Resource* resource) +{ + for (const auto& known : pass_of(self).states) + if (known.first == resource && (known.second & D3D12_RESOURCE_STATE_DEPTH_READ)) + return D3D12_RESOURCE_STATE_DEPTH_READ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; +} void use_as_target(Wrapper* self, ID3D12Resource* resource) { require_state(self, resource, D3D12_RESOURCE_STATE_RENDER_TARGET); } void release_targets(Wrapper* self) { @@ -1713,7 +1726,44 @@ DXGI_FORMAT view_format_of(u64 desktop_handle, ID3D12Resource* target) } return format; } +// The view a descriptor holds now, read from its shadow record so copies are followed. A record of the +// other kind is wrong_kind; a handle with no record falls back to the creation-time map (render targets only). +struct ResolvedView { + ID3D12Resource* resource = nullptr; + UINT dsv_flags = 0; + bool wrong_kind = false; +}; +ResolvedView resolve_view(u64 handle, int slot) +{ + ResolvedView out; + ViewRecord record{}; + bool known = false; + if (const std::uint32_t id = shadow_id(handle)) { + AcquireSRWLockShared(¬e_lock); + known = id - 1 < view_records().size(); + if (known) record = view_records()[id - 1]; + ReleaseSRWLockShared(¬e_lock); + } + if (!known) { + if (slot == 20) out.resource = view_target(handle, slot); + return out; + } + if (static_cast(record.slot) != slot) { + out.wrong_kind = true; + return out; + } + out.resource = record.resource ? reinterpret_cast(unwrap(record.resource)) : nullptr; + if (slot == 21 && record.desc_bytes >= 12) std::memcpy(&out.dsv_flags, record.desc + 8, 4); + return out; +} +bool format_has_stencil(DXGI_FORMAT format) +{ + return format == DXGI_FORMAT_D24_UNORM_S8_UINT || format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || + format == DXGI_FORMAT_R24G8_TYPELESS || format == DXGI_FORMAT_R32G8X24_TYPELESS; +} // List slot 50 (desktop 46 + 4), OMSetRenderTargets(count, handles, single range, depth). +// A descriptor of the wrong kind, a DSV with only one plane read-only (needs per-plane states), or a +// depth view that resolves to nothing refuses the whole bind: nothing is set and draws are skipped. void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* handles, BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* depth) { @@ -1725,12 +1775,15 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO pass.dsv_format = DXGI_FORMAT_UNKNOWN; if (!list || count > 8 || single_range) return; if (count && !x2w_local::readable(handles, count * sizeof(*handles))) return; + static LONG refused; D3D12_CPU_DESCRIPTOR_HANDLE desktop[8]; ID3D12Resource* targets[8]{}; DXGI_FORMAT formats[8]{}; for (UINT i = 0; i < count; ++i) { desktop[i].ptr = static_cast(desktop_cpu_handle(handles[i].ptr)); - targets[i] = view_target(desktop[i].ptr); + const ResolvedView view = resolve_view(desktop[i].ptr, 20); + if (view.wrong_kind && first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: render target %u is not a render target view", i); + targets[i] = view.resource; if (!targets[i]) return; formats[i] = view_format_of(desktop[i].ptr, targets[i]); } @@ -1738,13 +1791,27 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO const D3D12_CPU_DESCRIPTOR_HANDLE* dsv_ptr = nullptr; ID3D12Resource* dsv_target = nullptr; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; + D3D12_RESOURCE_STATES dsv_state = D3D12_RESOURCE_STATE_DEPTH_WRITE; if (depth && x2w_local::readable(depth, sizeof(*depth))) { const u64 resolved = desktop_cpu_handle(depth->ptr); - dsv_target = resolved ? view_target(resolved) : nullptr; - if (dsv_target) { + if (resolved) { + const ResolvedView view = resolve_view(resolved, 21); + dsv_target = view.resource; + if (!dsv_target) { + if (first_calls(refused, 6)) + log("x2w-d3d12 OMSetRenderTargets refused: depth handle is %s", view.wrong_kind ? "not a depth stencil view" : "not a known depth stencil view"); + return; + } + dsv_format = view_format_of(resolved, dsv_target); + const bool read_depth = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH) != 0; + const bool read_stencil = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) != 0 || !format_has_stencil(dsv_format); + if (read_depth != read_stencil) { + if (first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: depth stencil view with one read-only plane (flags 0x%x)", view.dsv_flags); + return; + } + if (read_depth) dsv_state = D3D12_RESOURCE_STATE_DEPTH_READ; desktop_dsv.ptr = static_cast(resolved); dsv_ptr = &desktop_dsv; - dsv_format = view_format_of(resolved, dsv_target); } } if (!count && !dsv_ptr) return; @@ -1753,7 +1820,7 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO pass.target_formats[i] = formats[i]; if (i == 0) pass.target0 = targets[i]; } - if (dsv_target) require_state(self, dsv_target, D3D12_RESOURCE_STATE_DEPTH_WRITE); + if (dsv_target) require_state(self, dsv_target, dsv_state); pass.target_count = count; pass.dsv_format = dsv_format; list->OMSetRenderTargets(count, count ? desktop : nullptr, FALSE, dsv_ptr); @@ -2242,7 +2309,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) args[1] = reinterpret_cast(&null_rtv); } const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); - if ((N == 20 || N == 21) && args[0]) note_view_target(args[D], reinterpret_cast(args[0])); + if ((N == 20 || N == 21) && args[0]) note_view_target(args[D], reinterpret_cast(args[0]), N); check_device("Device view", N); static LONG calls; if (first_calls(calls)) diff --git a/tests/startup_stream_depth.cpp b/tests/startup_stream_depth.cpp index e91ee8b7a..a53bb611e 100644 --- a/tests/startup_stream_depth.cpp +++ b/tests/startup_stream_depth.cpp @@ -93,7 +93,8 @@ int pick_adapter(bool hardware, ComPtr& adapter) } void* create_stream_pso(void* device, ID3D12RootSignature* root, const std::vector& vs, - const std::vector& ps, const D3D12_DEPTH_STENCIL_DESC& ds, bool use_ds1) + const std::vector& ps, const D3D12_DEPTH_STENCIL_DESC& ds, bool use_ds1, + BOOL depth_bounds = FALSE) { using CreateStream = HRESULT (WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); auto create = reinterpret_cast((*static_cast(device))[86]); @@ -103,7 +104,7 @@ void* create_stream_pso(void* device, ID3D12RootSignature* root, const std::vect {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}, - {static_cast(21), ds, FALSE}, + {static_cast(21), ds, depth_bounds}, {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT_D32_FLOAT}, }; const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; @@ -176,7 +177,7 @@ int execute_guest_list(void* queue, void* list, void* fence, UINT64 fence_value) int main(int argc, char** argv) { - if (argc != 7 && argc != 10) return 2; + if (argc != 7 && argc != 14) return 2; std::vector vs_front, vs_back, ps_green, ps_red; if (!read_bytes(argv[1], vs_front) || !read_bytes(argv[2], vs_back) || !read_bytes(argv[3], ps_green) || !read_bytes(argv[4], ps_red)) return 3; @@ -184,6 +185,15 @@ int main(int argc, char** argv) ComPtr adapter; if (const int rc = pick_adapter(hardware, adapter)) return rc; + { + DXGI_ADAPTER_DESC desc{}; + LARGE_INTEGER driver{}; + if (FAILED(adapter->GetDesc(&desc))) return 4; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls vendor=%04x device=%04x driver=%u.%u.%u.%u\n", desc.Description, desc.VendorId, desc.DeviceId, + HIWORD(driver.HighPart), LOWORD(driver.HighPart), HIWORD(driver.LowPart), LOWORD(driver.LowPart)); + std::fflush(stdout); + } std::array parameters{}; void* guest = nullptr; @@ -212,7 +222,9 @@ int main(int argc, char** argv) void* pso_front_off = create_stream_pso(guest, root, vs_front, ps_green, ds_disabled, false); void* pso_back_off = create_stream_pso(guest, root, vs_back, ps_red, ds_disabled, false); void* pso_front_ds1 = create_stream_pso(guest, root, vs_front, ps_green, ds_less, true); - if (!pso_front_less || !pso_back_less || !pso_front_off || !pso_back_off || !pso_front_ds1) return 9; + // DepthBoundsTestEnable has no translated equivalent: the pipeline is refused for drawing, not translated without it. + void* pso_front_bounds = create_stream_pso(guest, root, vs_front, ps_green, ds_less, true, TRUE); + if (!pso_front_bounds || !pso_front_less || !pso_back_less || !pso_front_off || !pso_back_off || !pso_front_ds1) return 9; if (argc == 7) return 0; ComPtr desktop; @@ -242,7 +254,7 @@ int main(int argc, char** argv) const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; Word backing, bytes; } rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}, - dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}, 0, 0}; + dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2}, 0, 0}; void* dsv_heap = nullptr; if (FAILED(static_cast(invoke(guest, 14, ptr_arg(&rtv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&state.rtv_heap)))) || FAILED(static_cast(invoke(guest, 14, ptr_arg(&dsv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&dsv_heap))))) return 22; @@ -253,6 +265,11 @@ int main(int argc, char** argv) const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_view{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; invoke(guest, 20, ptr_arg(state.attachments[0].texture.Get()), ptr_arg(&rtv_view), rtv.ptr); invoke(guest, 21, ptr_arg(depth_tex.Get()), ptr_arg(&dsv_view), dsv.ptr); + // A second view of the same texture, read-only: depth tests but is never written. + const D3D12_CPU_DESCRIPTOR_HANDLE dsv_read_only{dsv.ptr + desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV)}; + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_read_only_view{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, + D3D12_DSV_FLAG_READ_ONLY_DEPTH, {}}; + invoke(guest, 21, ptr_arg(depth_tex.Get()), ptr_arg(&dsv_read_only_view), dsv_read_only.ptr); D3D12_COMMAND_QUEUE_DESC qd{}; const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; @@ -264,7 +281,9 @@ int main(int argc, char** argv) const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; const D3D12_RECT rect{0, 0, 4, static_cast(height)}; - auto run_case = [&](UINT64 fence_val, const char* out_path, bool depth_only, void* first_pso, void* second_pso) -> int { + enum class Bind { normal, depth_only, read_only_depth, rtv_as_depth, dsv_as_target }; + auto run_case = [&](UINT64 fence_val, const char* out_path, Bind bind, void* first_pso, void* second_pso) -> int { + const bool depth_only = bind == Bind::depth_only; if (const int rc = clear_depth_desktop(desktop.Get(), depth_tex.Get())) return rc; if (FAILED(static_cast(invoke(state.allocator, 8)))) return 24; if (FAILED(static_cast(invoke(state.list, 139, ptr_arg(state.allocator))))) return 25; @@ -274,6 +293,12 @@ int main(int argc, char** argv) invoke(state.list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); if (depth_only) { invoke(state.list, 50, 0, 0, FALSE, ptr_arg(&dsv)); + } else if (bind == Bind::read_only_depth) { + invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, ptr_arg(&dsv_read_only)); + } else if (bind == Bind::rtv_as_depth) { + invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, ptr_arg(&rtv)); // an RTV where a DSV belongs + } else if (bind == Bind::dsv_as_target) { + invoke(state.list, 50, 1, ptr_arg(&dsv), FALSE, ptr_arg(&dsv)); // a DSV where an RTV belongs } else { invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, ptr_arg(&dsv)); } @@ -288,8 +313,13 @@ int main(int argc, char** argv) return read_stream_target(desktop.Get(), state, out_path); }; - if (const int rc = run_case(1, argv[7], false, pso_front_less, pso_back_less)) return rc; - if (const int rc = run_case(2, argv[8], false, pso_front_off, pso_back_off)) return rc; - if (const int rc = run_case(3, argv[9], true, pso_front_ds1, pso_back_less)) return rc; + if (const int rc = run_case(1, argv[7], Bind::normal, pso_front_less, pso_back_less)) return rc; + if (const int rc = run_case(2, argv[8], Bind::normal, pso_front_off, pso_back_off)) return rc; + if (const int rc = run_case(3, argv[9], Bind::depth_only, pso_front_ds1, pso_back_less)) return rc; + if (const int rc = run_case(4, argv[10], Bind::read_only_depth, pso_front_less, pso_back_less)) return rc; + // Controls: nothing may be drawn for a wrong descriptor kind or an enabled depth bounds test. + if (const int rc = run_case(5, argv[11], Bind::rtv_as_depth, pso_front_less, pso_back_less)) return rc; + if (const int rc = run_case(6, argv[12], Bind::dsv_as_target, pso_front_less, pso_back_less)) return rc; + if (const int rc = run_case(7, argv[13], Bind::normal, pso_front_bounds, pso_front_bounds)) return rc; return 0; } diff --git a/tests/startup_stream_depth_check.py b/tests/startup_stream_depth_check.py index e2a079b10..e02e1609f 100644 --- a/tests/startup_stream_depth_check.py +++ b/tests/startup_stream_depth_check.py @@ -24,8 +24,9 @@ def check(directory, consumer, backend): vs_front, vs_back, ps_green, ps_red, root = ( directory / name for name in ("vs_front", "vs_back", "ps_green", "ps_red", "root") ) - out_pos, out_neg, out_depthonly = ( - directory / name for name in ("pixels_pos", "pixels_neg", "pixels_depthonly") + out_pos, out_neg, out_depthonly, out_readonly, out_rtv_depth, out_dsv_target, out_bounds = ( + directory / name for name in ("pixels_pos", "pixels_neg", "pixels_depthonly", "pixels_readonly", + "pixels_rtv_as_depth", "pixels_dsv_as_target", "pixels_bounds") ) vs_front.write_bytes(vertex(0x3e800000)) # z = 0.25f vs_back.write_bytes(vertex(0x3f400000)) # z = 0.75f @@ -43,7 +44,8 @@ def check(directory, consumer, backend): raise RuntimeError(f"request run failed on {backend}: {req.returncode}\n{req.stderr}") subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) - run = subprocess.run(base_args + [str(out_pos), str(out_neg), str(out_depthonly)], + run = subprocess.run(base_args + [str(out_pos), str(out_neg), str(out_depthonly), str(out_readonly), + str(out_rtv_depth), str(out_dsv_target), str(out_bounds)], env=env, capture_output=True, text=True) print(run.stdout, end="") for line in run.stderr.splitlines(): @@ -63,6 +65,11 @@ def check(directory, consumer, backend): assert out_pos.read_bytes() == expected_pos, f"pos: {out_pos.read_bytes().hex()}" assert out_neg.read_bytes() == expected_neg, f"neg: {out_neg.read_bytes().hex()}" assert out_depthonly.read_bytes() == expected_depthonly, f"depthonly: {out_depthonly.read_bytes().hex()}" + # A read-only DSV tests but never writes: the far red triangle is not occluded by the near green one. + assert out_readonly.read_bytes() == expected_neg, f"readonly: {out_readonly.read_bytes().hex()}" + # Wrong descriptor kind and DepthBoundsTestEnable refuse the draw instead of drawing something else. + for name, path in (("rtv as depth", out_rtv_depth), ("dsv as target", out_dsv_target), ("depth bounds", out_bounds)): + assert path.read_bytes() == clear * 32, f"{name}: {path.read_bytes().hex()}" print(f"{backend}: depth LESS occluded far red (green), DepthEnable=FALSE overwrote (red), count=0 depth-only occluded far red (clear)") return 0 From bb82d0a60ec70758aa072fca96520115ce86891a Mon Sep 17 00:00:00 2001 From: ammar Date: Tue, 24 Nov 2026 13:43:36 +0200 Subject: [PATCH 054/775] cpu: lift RDFSBASE, RDGSBASE, WRFSBASE, WRGSBASE, and RDPID in cpu_switch_aot --- CMakeLists.txt | 17 +- docs/experiments.md | 19 + tests/cpu/switch_fsgsbase_rdpid.asm | 206 +++++++++ tests/cpu/switch_fsgsbase_rdpid.def | 20 + tests/cpu/switch_fsgsbase_rdpid_check.py | 519 +++++++++++++++++++++++ tools/cpu_switch_aot.py | 70 ++- 6 files changed, 838 insertions(+), 13 deletions(-) create mode 100644 tests/cpu/switch_fsgsbase_rdpid.asm create mode 100644 tests/cpu/switch_fsgsbase_rdpid.def create mode 100644 tests/cpu/switch_fsgsbase_rdpid_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 8acd8f3e7..b9cbf9069 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1535,7 +1535,7 @@ if(EXISTS "${INTAKE_PYTHON}") target_link_options(${image} PRIVATE /NOENTRY /NODEFAULTLIB /INCREMENTAL:NO) endfunction() function(cpu_translation image translator entry) - cmake_parse_arguments(BIND "FFX_DESTROY;IMAGE_DATA" + cmake_parse_arguments(BIND "FFX_DESTROY;IMAGE_DATA;HOST_CPU" "PROVIDER;SYMBOL;LINK_NAME;CALLBACK_OFFSET;IMPORT_ARGUMENTS;RETURN_BYTES;NAME;RANGES;SECOND_PROVIDER;SECOND_SYMBOL;SECOND_LINK_NAME;SECOND_IMPORT_ARGUMENTS;SECOND_RETURN_BYTES" "STACK_OUTPUT" ${ARGN}) if(NOT BIND_NAME) set(BIND_NAME ${image}_lifted) @@ -1574,6 +1574,9 @@ if(EXISTS "${INTAKE_PYTHON}") if(BIND_IMAGE_DATA) list(APPEND binding --image-data) endif() + if(BIND_HOST_CPU) + list(APPEND binding --host-cpu) + endif() set(lifted "${CMAKE_CURRENT_BINARY_DIR}/${BIND_NAME}.cpp") add_custom_command(OUTPUT "${lifted}" COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/${translator}.py" @@ -2105,6 +2108,18 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME cpu_aot_switch_bswap COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/switch_bswap_check.py" "$" "$" "$") + cpu_asm_fixture(cpu_switch_fsgsbase_rdpid switch_fsgsbase_rdpid) + cpu_translation(cpu_switch_fsgsbase_rdpid cpu_switch_aot + "rdfsbase_32,rdfsbase_64,rdgsbase_32,rdgsbase_64,wrfsbase_32_roundtrip,wrfsbase_64_roundtrip,wrgsbase_32_roundtrip,wrgsbase_64_roundtrip,wrfsgsbase_nonvolatile,rdpid_64,rdpid_twice,flag_preserve_fsgsbase_rdpid,unused_host_reads" + HOST_CPU) + add_test(NAME cpu_aot_switch_fsgsbase_rdpid COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/switch_fsgsbase_rdpid_check.py" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_switch_fsgsbase_rdpid PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_switch_fsgsbase_rdpid.txt") # BSF and BSR; the swapped build assembles three exports with the other scan and must follow the exchanged reference. foreach(variant IN ITEMS original swapped) cpu_asm_fixture(cpu_switch_bit_scans_${variant} switch_bit_scans) diff --git a/docs/experiments.md b/docs/experiments.md index eb780b857..158459028 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9685,3 +9685,22 @@ For the same nine-mip textures, slot 2 returns the byte offset of each mip withi cmake --build --preset release --target startup_stream_consumer startup_stub_xg_xs xg_swizzle_select_check ctest --preset release --no-tests=error --output-on-failure -R '^(startup_xg_bc_(array|chain)_(hardware|warp)|startup_xg_bc_tiling|xg_bc64_tiling_reference|startup_xg_bc7_layout)$' ``` + +## Host-CPU FSGSBASE and RDPID lifting in cpu_switch_aot + +[The switch translator](../tools/cpu_switch_aot.py) adds an opt-in `--host-cpu` (`host_cpu=True`) mode lifting `rdfsbase`, `rdgsbase`, `wrfsbase`, `wrgsbase` (32- and 64-bit register forms), and `rdpid` (64-bit register form) from `docs/coverage/x64_zen2.tsv` group `Integer` to the `` intrinsics (`_readfsbase_u32`, `_readfsbase_u64`, `_readgsbase_u32`, `_readgsbase_u64`, `_writefsbase_u32`, `_writefsbase_u64`, `_writegsbase_u32`, `_writegsbase_u64`, `_rdpid_u32`): + +- `rdfsbase` / `rdgsbase` / `rdpid` read into a `const volatile` temporary before assigning the destination (zero-extending 32-bit `rdfsbase`/`rdgsbase` and 64-bit `rdpid` into the full 64-bit register) so `/O2` preserves unreferenced reads and execution order. +- `wrfsbase` / `wrgsbase` record their operand as a source read (not a destination write), wrap the intrinsic in `std::atomic_signal_fence(std::memory_order_seq_cst)`, and reject undefined source registers. +- All five instructions are registered in `FLAG_NEUTRAL` so arithmetic flags are preserved across them, and all five are refused when `host_cpu` is omitted, when `rsp`/`esp` is addressed, when a `lock`/`rep`/`repne`/segment prefix is present, or when `rdpid` uses its 32-bit encoding. + +```powershell +cmake --build --preset dev --target cpu_switch_fsgsbase_rdpid cpu_switch_fsgsbase_rdpid_lifted +ctest --preset dev --no-tests=error -R '^cpu_aot_switch_fsgsbase_rdpid$' -V +``` + +### Measured results and open scope + +The [MASM fixture](../tests/cpu/switch_fsgsbase_rdpid.asm) exports 13 translated functions covering 32- and 64-bit `rdfsbase`/`rdgsbase` (with high-bit prefill), canonical `wrfsbase`/`wrgsbase` round-trips that save and restore `FS_BASE` and the Windows TEB `GS_BASE`, nonvolatile `rbx`/`r12` save/restore, `rdpid` single and repeated reads, `FLAG_NEUTRAL` flag preservation across `add` to `setb`/`sete`/`sets`/`seto`/`setp`, and unused reads, plus native `CPUID.07H` and `RDTSCP` helpers and four rejected negative exports. [The differential check](../tests/cpu/switch_fsgsbase_rdpid_check.py) exits 77 if `CPUID.07H` lacks `FSGSBASE` (`EBX[0]`) or `RDPID` (`ECX[22]`) and otherwise pins the thread to up to four logical processors, verifying 376 CMake-lifted and 376 `/O2`-lifted checks across `dev` and `release` builds against native execution and `RDTSCP` `IA32_TSC_AUX` (while preserving `FS_BASE`/`GS_BASE` on every call), four `/O2` mutated-C++ negative controls (`keep_high32`, `drop_wrfsgsbase`, `constant_rdpid`, `clobber_flags`), 20 unit rejection controls, and 6 PE-patched DLL rejection controls, while recording decoded mnemonics through `FORM_COVERAGE_RECORD`. + +Not covered by this experiment: non-canonical `wrfsbase`/`wrgsbase` `#GP` fault behavior, cross-thread `FS_BASE`/`GS_BASE` migration, and title CPU code execution. diff --git a/tests/cpu/switch_fsgsbase_rdpid.asm b/tests/cpu/switch_fsgsbase_rdpid.asm new file mode 100644 index 000000000..0d653c706 --- /dev/null +++ b/tests/cpu/switch_fsgsbase_rdpid.asm @@ -0,0 +1,206 @@ +; coverage: record cpu_aot_switch_fsgsbase_rdpid +; Source-built MASM fixture for RDFSBASE, RDGSBASE, WRFSBASE, WRGSBASE, and RDPID +; in tools/cpu_switch_aot.py (--host-cpu opt-in), plus native CPUID/RDTSCP helpers +; and negative controls. +; Every translated export uses the Windows x64 ABI: RCX, RDX, R8 -> RAX. +.code + +; --- Translated positive exports --- + +rdfsbase_32 PROC FRAME + .endprolog + mov rax, -1 + rdfsbase eax + ret +rdfsbase_32 ENDP + +rdfsbase_64 PROC FRAME + .endprolog + rdfsbase rax + ret +rdfsbase_64 ENDP + +rdgsbase_32 PROC FRAME + .endprolog + mov rax, -1 + rdgsbase eax + ret +rdgsbase_32 ENDP + +rdgsbase_64 PROC FRAME + .endprolog + rdgsbase rax + ret +rdgsbase_64 ENDP + +wrfsbase_32_roundtrip PROC FRAME + .endprolog + rdfsbase r9 + wrfsbase ecx + mov rax, -1 + rdfsbase rax + wrfsbase r9 + ret +wrfsbase_32_roundtrip ENDP + +wrfsbase_64_roundtrip PROC FRAME + .endprolog + rdfsbase r9 + wrfsbase rcx + rdfsbase rax + wrfsbase r9 + ret +wrfsbase_64_roundtrip ENDP + +wrgsbase_32_roundtrip PROC FRAME + .endprolog + rdgsbase r9 + wrgsbase ecx + mov rax, -1 + rdgsbase rax + wrgsbase r9 + ret +wrgsbase_32_roundtrip ENDP + +wrgsbase_64_roundtrip PROC FRAME + .endprolog + rdgsbase r9 + wrgsbase rcx + rdgsbase rax + wrgsbase r9 + ret +wrgsbase_64_roundtrip ENDP + +wrfsgsbase_nonvolatile PROC FRAME + push rbx + .pushreg rbx + push r12 + .pushreg r12 + .endprolog + rdfsbase rbx + rdgsbase r12 + wrfsbase rcx + rdfsbase r10 + wrfsbase rbx + wrgsbase rdx + rdgsbase r11 + wrgsbase r12 + mov QWORD PTR [r8], r10 + mov QWORD PTR [r8+8], r11 + mov rax, r10 + xor rax, r11 + pop r12 + pop rbx + ret +wrfsgsbase_nonvolatile ENDP + +rdpid_64 PROC FRAME + .endprolog + mov rax, -1 + rdpid rax + ret +rdpid_64 ENDP + +rdpid_twice PROC FRAME + .endprolog + rdpid r9 + rdpid r10 + mov QWORD PTR [r8], r9 + mov QWORD PTR [r8+8], r10 + mov rax, r9 + ret +rdpid_twice ENDP + +flag_preserve_fsgsbase_rdpid PROC FRAME + .endprolog + rdfsbase r9 + rdgsbase r10 + add rcx, rdx + rdfsbase rax + rdgsbase r11 + wrfsbase r9 + wrgsbase r10 + rdpid r11 + setb BYTE PTR [r8] + sete BYTE PTR [r8+1] + sets BYTE PTR [r8+2] + seto BYTE PTR [r8+3] + setp BYTE PTR [r8+4] + mov rax, rcx + ret +flag_preserve_fsgsbase_rdpid ENDP + +unused_host_reads PROC FRAME + .endprolog + rdfsbase r10 + rdgsbase r10 + rdpid r10 + mov eax, 42 + ret +unused_host_reads ENDP + +; --- Native-only host CPUID / RDTSCP helpers (never translated) --- + +native_host_features PROC FRAME + push rbx + .pushreg rbx + .endprolog + xor eax, eax + cpuid + xor r8d, r8d + cmp eax, 7 + jb done_features + mov eax, 7 + xor ecx, ecx + cpuid + test ebx, 1 + jz check_rdpid + or r8d, 1 +check_rdpid: + bt ecx, 22 + jnc done_features + or r8d, 2 +done_features: + mov eax, r8d + pop rbx + ret +native_host_features ENDP + +native_rdtscp_aux PROC FRAME + .endprolog + rdtscp + mov eax, ecx + ret +native_rdtscp_aux ENDP + +; --- Negative controls (refused by translator; never translated in build) --- + +neg_undef_wrfsbase PROC FRAME + .endprolog + wrfsbase r10 + xor eax, eax + ret +neg_undef_wrfsbase ENDP + +neg_undef_wrgsbase PROC FRAME + .endprolog + wrgsbase r11d + xor eax, eax + ret +neg_undef_wrgsbase ENDP + +neg_rsp_rdfsbase PROC FRAME + .endprolog + rdfsbase rsp + xor eax, eax + ret +neg_rsp_rdfsbase ENDP + +neg_rsp_rdpid PROC FRAME + .endprolog + rdpid rsp + xor eax, eax + ret +neg_rsp_rdpid ENDP + +END diff --git a/tests/cpu/switch_fsgsbase_rdpid.def b/tests/cpu/switch_fsgsbase_rdpid.def new file mode 100644 index 000000000..83df7e1f1 --- /dev/null +++ b/tests/cpu/switch_fsgsbase_rdpid.def @@ -0,0 +1,20 @@ +EXPORTS + rdfsbase_32 + rdfsbase_64 + rdgsbase_32 + rdgsbase_64 + wrfsbase_32_roundtrip + wrfsbase_64_roundtrip + wrgsbase_32_roundtrip + wrgsbase_64_roundtrip + wrfsgsbase_nonvolatile + rdpid_64 + rdpid_twice + flag_preserve_fsgsbase_rdpid + unused_host_reads + native_host_features + native_rdtscp_aux + neg_undef_wrfsbase + neg_undef_wrgsbase + neg_rsp_rdfsbase + neg_rsp_rdpid diff --git a/tests/cpu/switch_fsgsbase_rdpid_check.py b/tests/cpu/switch_fsgsbase_rdpid_check.py new file mode 100644 index 000000000..6fec9cd7c --- /dev/null +++ b/tests/cpu/switch_fsgsbase_rdpid_check.py @@ -0,0 +1,519 @@ +"""Differential checks, mutated-C++ controls, and unit/PE rejection controls +for RDFSBASE, RDGSBASE, WRFSBASE, WRGSBASE, and RDPID in tools/cpu_switch_aot.py. +""" + +import ctypes +import os +from pathlib import Path +import re +import subprocess +import sys +from tempfile import TemporaryDirectory + +import pefile +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, Register as R + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva +from cpu_switch_aot import Lifter, translate + +U64 = ctypes.c_uint64 +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF + +TRANSLATED_EXPORTS = ( + "rdfsbase_32", + "rdfsbase_64", + "rdgsbase_32", + "rdgsbase_64", + "wrfsbase_32_roundtrip", + "wrfsbase_64_roundtrip", + "wrgsbase_32_roundtrip", + "wrgsbase_64_roundtrip", + "wrfsgsbase_nonvolatile", + "rdpid_64", + "rdpid_twice", + "flag_preserve_fsgsbase_rdpid", + "unused_host_reads", +) + +CANONICAL_64_VALUES = ( + 0x0000000000000000, + 0x0000000012345678, + 0x0000000080000001, + 0x0000123456789ABC, + 0x00007FFFFFFFFFF0, + 0xFFFF800012345678, + 0xFFFFFFFF80000001, +) + +WR32_VALUES = ( + 0x0000000000000000, + 0x0000000012345678, + 0x0000000080000001, + 0x00007FFF80000001, + 0xDEAD0000BEEF1234, + 0xFFFFFFFFFFFFFFFF, +) + +FLAG_PAIRS = ( + (0, 0), + (1, 0), + (0xFFFFFFFFFFFFFFFF, 1), + (0x7FFFFFFFFFFFFFFF, 1), + (0x8000000000000000, 0x8000000000000000), + (0x5555555555555555, 0xAAAAAAAAAAAAAAAA), + (0x123456789ABCDEF0, 0x0FEDCBA987654321), +) + + +def even_parity_byte(v): + return (bin(v & 0xFF).count("1") % 2) == 0 + + +def expected_add_flags(a, b): + total = (a + b) & MASK64 + cf = int((a + b) > MASK64) + zf = int(total == 0) + sf = int((total >> 63) & 1) + of = int((((~(a ^ b)) & (a ^ total)) >> 63) & 1) + pf = int(even_parity_byte(total)) + return total, bytes((cf, zf, sf, of, pf)) + + +def bind_lib(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in TRANSLATED_EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [U64, U64, U64] + fn.restype = U64 + funcs[name] = fn + if not prefix: + for helper in ("native_host_features", "native_rdtscp_aux"): + fn = getattr(lib, helper) + fn.argtypes = [U64, U64, U64] + fn.restype = U64 + funcs[helper] = fn + return lib, funcs + + +def logical_cpus(): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetCurrentProcess.restype = ctypes.c_void_p + kernel32.GetCurrentThread.restype = ctypes.c_void_p + kernel32.GetProcessAffinityMask.argtypes = [ + ctypes.c_void_p, + ctypes.POINTER(ctypes.c_size_t), + ctypes.POINTER(ctypes.c_size_t), + ] + kernel32.SetThreadAffinityMask.argtypes = [ctypes.c_void_p, ctypes.c_size_t] + kernel32.SetThreadAffinityMask.restype = ctypes.c_size_t + kernel32.GetCurrentProcessorNumber.restype = ctypes.c_uint32 + process, system = ctypes.c_size_t(), ctypes.c_size_t() + if not kernel32.GetProcessAffinityMask( + kernel32.GetCurrentProcess(), ctypes.byref(process), ctypes.byref(system) + ): + raise OSError(ctypes.get_last_error(), "GetProcessAffinityMask") + cpus = [k for k in range(process.value.bit_length()) if (process.value >> k) & 1] + return kernel32, process.value, cpus + + +def pin_to_cpu(kernel32, cpu): + prev = kernel32.SetThreadAffinityMask(kernel32.GetCurrentThread(), 1 << cpu) + if not prev: + raise OSError(ctypes.get_last_error(), "SetThreadAffinityMask") + for _ in range(200): + running = kernel32.GetCurrentProcessorNumber() + if running == cpu: + return prev + kernel32.Sleep(1) + raise AssertionError(f"pinned to logical processor {cpu}, still running on {running}") + + +def verify_exports(native_fns, target_fns, label, cpus): + """Run all differential checks for target_fns against native_fns across pinned CPUs.""" + kernel32, full_mask, _ = logical_cpus() + saved_affinity = None + total_checks = 0 + try: + for cpu in cpus: + prev = pin_to_cpu(kernel32, cpu) + if saved_affinity is None: + saved_affinity = prev + + # 1) Direct FS/GS base reads + 32-bit zero-extension + base_fs = native_fns["rdfsbase_64"](0, 0, 0) + base_gs = native_fns["rdgsbase_64"](0, 0, 0) + if base_gs == 0: + raise AssertionError(f"{label}: expected non-zero TEB GS_BASE on Windows x64") + for tag, fns in (("native", native_fns), (label, target_fns)): + got_fs64 = fns["rdfsbase_64"](0, 0, 0) + got_gs64 = fns["rdgsbase_64"](0, 0, 0) + got_fs32 = fns["rdfsbase_32"](0, 0, 0) + got_gs32 = fns["rdgsbase_32"](0, 0, 0) + if got_fs64 != base_fs or got_gs64 != base_gs: + raise AssertionError( + f"{tag} read base mismatch on cpu {cpu}: " + f"fs={got_fs64:#x}!={base_fs:#x}, gs={got_gs64:#x}!={base_gs:#x}" + ) + if got_fs32 != (base_fs & MASK32) or got_gs32 != (base_gs & MASK32): + raise AssertionError( + f"{tag} 32-bit read did not zero-extend on cpu {cpu}: " + f"fs32={got_fs32:#x}, gs32={got_gs32:#x}" + ) + total_checks += 4 + + # 2) Canonical FS/GS round-trips (preserving TEB GS_BASE & FS_BASE across every call) + for tag, fns in (("native", native_fns), (label, target_fns)): + for val in WR32_VALUES: + got_fs = fns["wrfsbase_32_roundtrip"](val, 0, 0) + got_gs = fns["wrgsbase_32_roundtrip"](val, 0, 0) + want = val & MASK32 + if got_fs != want or got_gs != want: + raise AssertionError( + f"{tag} wr*base_32({val:#x}): got fs={got_fs:#x}, gs={got_gs:#x}, want={want:#x}" + ) + if native_fns["rdfsbase_64"](0, 0, 0) != base_fs or native_fns["rdgsbase_64"](0, 0, 0) != base_gs: + raise AssertionError(f"{tag} wr*base_32 failed to restore FS_BASE/TEB GS_BASE") + total_checks += 2 + + for val in CANONICAL_64_VALUES: + got_fs = fns["wrfsbase_64_roundtrip"](val, 0, 0) + got_gs = fns["wrgsbase_64_roundtrip"](val, 0, 0) + if got_fs != val or got_gs != val: + raise AssertionError( + f"{tag} wr*base_64({val:#x}): got fs={got_fs:#x}, gs={got_gs:#x}" + ) + if native_fns["rdfsbase_64"](0, 0, 0) != base_fs or native_fns["rdgsbase_64"](0, 0, 0) != base_gs: + raise AssertionError(f"{tag} wr*base_64 failed to restore FS_BASE/TEB GS_BASE") + total_checks += 2 + + out_nv = (U64 * 2)() + for fs_v, gs_v in zip(CANONICAL_64_VALUES, reversed(CANONICAL_64_VALUES)): + got_xor = fns["wrfsgsbase_nonvolatile"](fs_v, gs_v, ctypes.addressof(out_nv)) + if got_xor != (fs_v ^ gs_v) or out_nv[0] != fs_v or out_nv[1] != gs_v: + raise AssertionError( + f"{tag} wrfsgsbase_nonvolatile({fs_v:#x}, {gs_v:#x}): " + f"got ({got_xor:#x}, {out_nv[0]:#x}, {out_nv[1]:#x})" + ) + if native_fns["rdfsbase_64"](0, 0, 0) != base_fs or native_fns["rdgsbase_64"](0, 0, 0) != base_gs: + raise AssertionError(f"{tag} wrfsgsbase_nonvolatile failed to restore FS_BASE/TEB GS_BASE") + total_checks += 1 + + # 3) RDPID cross-checked against pinned RDTSCP IA32_TSC_AUX + aux = native_fns["native_rdtscp_aux"](0, 0, 0) + out_pid = (U64 * 2)() + for tag, fns in (("native", native_fns), (label, target_fns)): + pid1 = fns["rdpid_64"](0, 0, 0) + pid2 = fns["rdpid_twice"](0, 0, ctypes.addressof(out_pid)) + if pid1 != aux or pid2 != aux or out_pid[0] != aux or out_pid[1] != aux: + raise AssertionError( + f"{tag} rdpid mismatch on cpu {cpu}: pid1={pid1:#x}, pid2={pid2:#x}, " + f"buf=({out_pid[0]:#x}, {out_pid[1]:#x}), rdtscp_aux={aux:#x}" + ) + total_checks += 2 + + # 4) FLAG_NEUTRAL flag preservation across all five instructions + flag_buf = ctypes.create_string_buffer(8) + for tag, fns in (("native", native_fns), (label, target_fns)): + for a, b in FLAG_PAIRS: + exp_sum, exp_flags = expected_add_flags(a, b) + got_sum = fns["flag_preserve_fsgsbase_rdpid"](a, b, ctypes.addressof(flag_buf)) + got_flags = flag_buf.raw[:5] + if got_sum != exp_sum or got_flags != exp_flags: + raise AssertionError( + f"{tag} flag_preserve({a:#x}, {b:#x}): " + f"sum={got_sum:#x}!={exp_sum:#x}, flags={got_flags.hex()}!={exp_flags.hex()}" + ) + total_checks += 1 + + # 5) Unused host-CPU reads must still compile and return 42 + for tag, fns in (("native", native_fns), (label, target_fns)): + got_unused = fns["unused_host_reads"](0, 0, 0) + if got_unused != 42: + raise AssertionError(f"{tag} unused_host_reads returned {got_unused}, expected 42") + total_checks += 1 + finally: + if saved_affinity is not None: + kernel32.SetThreadAffinityMask(kernel32.GetCurrentThread(), full_mask) + return total_checks + + +def compile_cpp_dll(cxx_path, cpp_path, dll_path, opt_flag="/O2"): + obj_path = dll_path.with_suffix(".obj") + cmd = [ + str(cxx_path), + "/nologo", + opt_flag, + "/W4", + "/LD", + str(cpp_path), + f"/Fo{obj_path}", + f"/Fe{dll_path}", + ] + res = subprocess.run(cmd, capture_output=True, text=True) + if res.returncode: + raise AssertionError(f"failed to compile {cpp_path.name}:\n{res.stdout}\n{res.stderr}") + + +def build_mutated_sources(base_source): + """Create four C++ mutants that each break one required semantic invariant.""" + mutants = {} + + # 1) Keep high 32 bits instead of zero-extending on RDFSBASE/RDGSBASE 32-bit and RDPID. + src_keep, n1a = re.subn( + r"(\w+) = static_cast\(base\);", + r"\1 = (\1 & ~0xffffffffull) | static_cast(base);", + base_source, + ) + src_keep, n1b = re.subn( + r"(\w+) = static_cast\(pid\);", + r"\1 = (\1 & ~0xffffffffull) | static_cast(pid);", + src_keep, + ) + if n1a != 2 or n1b < 3: + raise AssertionError(f"keep_high32 mutant expected 2 base + >=3 pid replacements, got {n1a}, {n1b}") + mutants["keep_high32"] = src_keep + + # 2) Drop WRFSBASE/WRGSBASE writes (no-op). + src_drop, n2 = re.subn( + r"_write(fs|gs)base_u(32|64)\(([^;]+)\);", + r"static_cast(\3);", + base_source, + ) + if n2 < 4: + raise AssertionError(f"drop_wrfsgsbase mutant expected >= 4 replacements, got {n2}") + mutants["drop_wrfsgsbase"] = src_drop + + # 3) Constant RDPID instead of reading IA32_TSC_AUX. + src_pid, n3 = re.subn(r"_rdpid_u32\(\)", "0x13572468u", base_source) + if n3 < 2: + raise AssertionError(f"constant_rdpid mutant expected >= 2 replacements, got {n3}") + mutants["constant_rdpid"] = src_pid + + # 4) Clobber arithmetic flags inside lifted_flag_preserve_fsgsbase_rdpid. + marker = "lifted_flag_preserve_fsgsbase_rdpid(" + head, rest = base_source.split(marker, 1) + body, tail = rest.split("\n}", 1) + body_mut, n4 = re.subn( + r"(const volatile std::uint32_t pid = _rdpid_u32\(\);[^\n]+\n)", + r"\1 fa = 0; fb = 1;\n", + body, + count=1, + ) + if n4 != 1: + raise AssertionError("clobber_flags mutant failed to anchor on _rdpid_u32 in flag_preserve") + mutants["clobber_flags"] = head + marker + body_mut + "\n}" + tail + + return mutants + + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(native_path): + # 1) Default profile (host_cpu omitted) must refuse all five instructions. + for name in ("rdfsbase_64", "rdgsbase_64", "wrfsbase_64_roundtrip", "wrgsbase_64_roundtrip", "rdpid_64"): + try: + translate(native_path, [name]) + except ValueError as exc: + if "requires host_cpu=True" not in str(exc): + raise AssertionError(f"default profile {name}: unexpected {exc!r}") from exc + else: + raise AssertionError(f"default profile unexpectedly accepted {name}") + + # 2) MASM negative exports (undefined source on WRFSBASE/WRGSBASE, RSP operand). + masm_refusals = ( + ("neg_undef_wrfsbase", "undefined register r10"), + ("neg_undef_wrgsbase", "undefined register r11"), + ("neg_rsp_rdfsbase", "rsp"), + ("neg_rsp_rdpid", "rsp"), + ) + for name, expected_reason in masm_refusals: + try: + translate(native_path, [name], host_cpu=True) + except ValueError as exc: + if expected_reason not in str(exc).lower(): + raise AssertionError(f"{name}: expected {expected_reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{name}: translator unexpectedly accepted negative export") + + # 3) Unit Lifter.lower rejections: host_cpu omitted, RSP/ESP, prefixes, RDPID_R32. + unit_insns = [ + ("lower_default_rdfsbase", Instruction.create_reg(Code.RDFSBASE_R64, R.RAX), False, "requires host_cpu=True"), + ("lower_default_rdgsbase", Instruction.create_reg(Code.RDGSBASE_R32, R.EAX), False, "requires host_cpu=True"), + ("lower_default_wrfsbase", Instruction.create_reg(Code.WRFSBASE_R64, R.RCX), False, "requires host_cpu=True"), + ("lower_default_wrgsbase", Instruction.create_reg(Code.WRGSBASE_R32, R.ECX), False, "requires host_cpu=True"), + ("lower_default_rdpid", Instruction.create_reg(Code.RDPID_R64, R.RAX), False, "requires host_cpu=True"), + ("lower_rsp_rdfsbase", Instruction.create_reg(Code.RDFSBASE_R64, R.RSP), True, "unsupported use of rsp"), + ("lower_esp_rdgsbase", Instruction.create_reg(Code.RDGSBASE_R32, R.ESP), True, "unsupported use of rsp"), + ("lower_rsp_wrfsbase", Instruction.create_reg(Code.WRFSBASE_R64, R.RSP), True, "unsupported use of rsp"), + ("lower_esp_wrgsbase", Instruction.create_reg(Code.WRGSBASE_R32, R.ESP), True, "unsupported use of rsp"), + ("lower_rsp_rdpid", Instruction.create_reg(Code.RDPID_R64, R.RSP), True, "unsupported use of rsp"), + ("lower_rdpid_r32", Instruction.create_reg(Code.RDPID_R32, R.EAX), True, "unsupported RDPID encoding"), + ] + for label, ins, opt_in, reason in unit_insns: + try: + Lifter(host_cpu=opt_in).lower(ins) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: Lifter.lower unexpectedly accepted {ins}") + + # Segment / REP / LOCK prefixes on FSGSBASE and RDPID. + gs_rdfsbase = Instruction.create_reg(Code.RDFSBASE_R32, R.EAX) + gs_rdfsbase.segment_prefix = R.GS + gs_rdpid = Instruction.create_reg(Code.RDPID_R64, R.RAX) + gs_rdpid.segment_prefix = R.GS + rep_wrfsbase = Instruction.create_reg(Code.WRFSBASE_R64, R.RCX) + rep_wrfsbase.has_rep_prefix = True + repne_rdgsbase = Instruction.create_reg(Code.RDGSBASE_R64, R.RAX) + repne_rdgsbase.has_repne_prefix = True + for label, ins in ( + ("seg_rdfsbase", gs_rdfsbase), + ("seg_rdpid", gs_rdpid), + ("rep_wrfsbase", rep_wrfsbase), + ("repne_rdgsbase", repne_rdgsbase), + ): + try: + Lifter(host_cpu=True).lower(ins) + except ValueError as exc: + if "unsupported instruction prefix" not in str(exc): + raise AssertionError(f"{label}: expected prefix rejection, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: Lifter.lower unexpectedly accepted prefixed {ins}") + + # 4) End-to-end PE-patched DLL rejections (patching wrfsgsbase_nonvolatile). + pe_bytes = Path(native_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "wrfsgsbase_nonvolatile") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) + if int.from_bytes(records[i:i + 4], "little") == entry) + pdata_end_off = pe.get_offset_from_rva(pdata.VirtualAddress + rec_idx + 4) + orig_end = int.from_bytes(records[rec_idx + 4:rec_idx + 8], "little") + max_len = orig_end - entry + + ret_bytes = encode_seq(Instruction.create(Code.RETNQ)) + pe_patches = [ + ("pe_seg_rdfsbase", bytes.fromhex("65f30faec0") + ret_bytes, "unsupported instruction prefix"), + ("pe_seg_rdpid", bytes.fromhex("65f30fc7f8") + ret_bytes, "unsupported instruction prefix"), + ("pe_lock_rdfsbase", bytes.fromhex("f0f30faec0") + ret_bytes, "invalid"), + ("pe_rsp_rdfsbase", bytes.fromhex("f3480faec4") + ret_bytes, "frame"), + ("pe_rsp_rdpid", bytes.fromhex("f30fc7fc") + ret_bytes, "frame"), + ("pe_undef_wrfsbase", bytes.fromhex("f3490faed2") + ret_bytes, "undefined register"), + ] + with TemporaryDirectory() as folder: + patched_path = Path(folder) / "patched.dll" + for label, patch, reason in pe_patches: + if len(patch) > max_len: + raise AssertionError(f"{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + damaged[pdata_end_off:pdata_end_off + 4] = (entry + len(patch)).to_bytes(4, "little") + patched_path.write_bytes(damaged) + try: + translate(patched_path, ["wrfsgsbase_nonvolatile"], host_cpu=True) + except ValueError as exc: + if reason not in str(exc).lower(): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: PE translate unexpectedly accepted patched bytes") + + print(f"20 unit rejections (5 default-profile, 4 MASM negative, 11 Lifter.lower/prefix) " + f"and {len(pe_patches)} PE-patched rejections passed") + + +def record_covered_forms(native_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(native_path), fast_load=True) as pe: + for name in TRANSLATED_EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def main(): + native_path, lifted_path, cxx_path = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]) + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + _, native_fns = bind_lib(native_path) + features = native_fns["native_host_features"](0, 0, 0) + if (features & 3) != 3: + print(f"host lacks CPUID.07H FSGSBASE/RDPID (mask={features:#x}); skipping") + raise SystemExit(77) + + _, lifted_fns = bind_lib(lifted_path, "lifted_") + _, _, all_cpus = logical_cpus() + cpus = all_cpus[:4] if len(all_cpus) > 4 else all_cpus + + checked_cmake = verify_exports(native_fns, lifted_fns, "lifted_cmake", cpus) + + # Also build /O2 and the 4 mutated C++ negative control DLLs directly from cpu_switch_aot. + source_text, _ = translate(native_path, list(TRANSLATED_EXPORTS), host_cpu=True) + mutants = build_mutated_sources(source_text) + with TemporaryDirectory() as folder: + tmp = Path(folder) + o2_cpp = tmp / "lifted_o2.cpp" + o2_dll = tmp / "lifted_o2.dll" + o2_cpp.write_text(source_text, encoding="utf-8") + compile_cpp_dll(cxx_path, o2_cpp, o2_dll, "/O2") + o2_lib, o2_fns = bind_lib(o2_dll, "lifted_") + try: + checked_o2 = verify_exports(native_fns, o2_fns, "lifted_o2", cpus) + finally: + o2_fns.clear() + unload_lib(o2_lib) + + for mut_name, mut_src in mutants.items(): + mut_cpp = tmp / f"{mut_name}.cpp" + mut_dll = tmp / f"{mut_name}.dll" + mut_cpp.write_text(mut_src, encoding="utf-8") + compile_cpp_dll(cxx_path, mut_cpp, mut_dll, "/O2") + mut_lib, mut_fns = bind_lib(mut_dll, "lifted_") + try: + try: + verify_exports(native_fns, mut_fns, f"mutant_{mut_name}", cpus[:1]) + except AssertionError as exc: + print(f"mutant {mut_name} caught: {exc}") + else: + raise AssertionError(f"mutant {mut_name} unexpectedly passed all checks") + finally: + mut_fns.clear() + unload_lib(mut_lib) + + check_rejections(native_path) + record_covered_forms(native_path) + print(f"verified {checked_cmake} CMake-lifted + {checked_o2} /O2-lifted checks across " + f"{len(cpus)} pinned CPU(s), 4 mutated-C++ controls, and all rejections") + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_switch_aot.py b/tools/cpu_switch_aot.py index 421ea2933..08fdfe978 100644 --- a/tools/cpu_switch_aot.py +++ b/tools/cpu_switch_aot.py @@ -248,7 +248,18 @@ # Instructions that neither read nor write the arithmetic flags, besides SETcc and CMOVcc, # which only read them. FLAG_NEUTRAL = {M.CLZERO, M.MOV, M.MOVZX, M.MOVSX, M.MOVSXD, M.LEA, M.NOP, M.NOT, M.BSWAP, *SETCC, *CMOVCC, *SIGN_EXTENSIONS, - M.MOVSB, M.MOVSW, M.MOVSD, M.MOVSQ, M.STOSB, M.STOSW, M.STOSD, M.STOSQ, M.CLD, M.STD, M.LEAVE} + M.MOVSB, M.MOVSW, M.MOVSD, M.MOVSQ, M.STOSB, M.STOSW, M.STOSD, M.STOSQ, M.CLD, M.STD, M.LEAVE, + M.RDFSBASE, M.RDGSBASE, M.WRFSBASE, M.WRGSBASE, M.RDPID} +HOST_CPU_FSGSBASE_CODES = { + Code.RDFSBASE_R32: ("_readfsbase_u32", False, 4), + Code.RDFSBASE_R64: ("_readfsbase_u64", False, 8), + Code.RDGSBASE_R32: ("_readgsbase_u32", False, 4), + Code.RDGSBASE_R64: ("_readgsbase_u64", False, 8), + Code.WRFSBASE_R32: ("_writefsbase_u32", True, 4), + Code.WRFSBASE_R64: ("_writefsbase_u64", True, 8), + Code.WRGSBASE_R32: ("_writegsbase_u32", True, 4), + Code.WRGSBASE_R64: ("_writegsbase_u64", True, 8), +} FLAG_PRODUCERS = {*ALU, M.CMP, M.TEST, M.INC, M.DEC, M.NEG, *SHIFTS, *BIT_TESTS, *BIT_COUNTS, *BIT_SCANS} MAX_FLAG_DISTANCE = 16 CONDITIONS = {CC.O: "o", CC.NO: "no", CC.P: "p", CC.NP: "np", @@ -883,9 +894,10 @@ def image_target(pe, ins): class Lifter: - def __init__(self, image=None): + def __init__(self, image=None, *, host_cpu=False): self.used = set() self.flags = False + self.host_cpu = host_cpu # The input image when RIP-relative operands address the bound mapping, and whether one does. self.image = image self.image_used = False @@ -1106,6 +1118,34 @@ def lower(self, ins, sets_flags=False, producer=None): # even when a following iteration or caller overwrites the same line. return (f"{{ auto* line = reinterpret_cast({address} & ~63ull); " "for (unsigned i = 0; i < 64; ++i) line[i] = 0; }", {R.RAX: 8}, {}) + if mnemonic in (M.RDFSBASE, M.RDGSBASE, M.WRFSBASE, M.WRGSBASE, M.RDPID): + if not self.host_cpu: + raise ValueError(f"{str(ins).split()[0].upper()} requires host_cpu=True (--host-cpu) at RVA {ins.ip:#x}") + if (ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix + or ins.has_segment_prefix or ins.has_xacquire_prefix or ins.has_xrelease_prefix): + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}") + if ins.op_count != 1 or ins.op0_kind != OpKind.REGISTER: + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + dest_reg = ins.op0_register + if full(dest_reg) == R.RSP: + raise ValueError(f"unsupported use of rsp at RVA {ins.ip:#x}") + if mnemonic == M.RDPID: + if ins.code != Code.RDPID_R64: + raise ValueError(f"unsupported RDPID encoding at RVA {ins.ip:#x}: {ins}") + line = f"{{ const volatile std::uint32_t pid = _rdpid_u32(); {self.write(ins, 8, 'pid')} }}" + return line, {}, {full(dest_reg): 8} + if ins.code not in HOST_CPU_FSGSBASE_CODES: + raise ValueError(f"unsupported FSGSBASE encoding at RVA {ins.ip:#x}: {ins}") + intrinsic, is_write, op_width = HOST_CPU_FSGSBASE_CODES[ins.code] + if is_write: + val = self.reg(dest_reg) + line = (f"{{ std::atomic_signal_fence(std::memory_order_seq_cst); " + f"{intrinsic}({val}); " + f"std::atomic_signal_fence(std::memory_order_seq_cst); }}") + return line, {full(dest_reg): op_width}, {} + u = unsigned(op_width) + line = f"{{ const volatile {u} base = {intrinsic}(); {self.write(ins, op_width, 'base')} }}" + return line, {}, {full(dest_reg): op_width} if ins.code in STRING_TRANSFERS: kind, width = STRING_TRANSFERS[ins.code] if (ins.has_segment_prefix or ins.has_repne_prefix or ins.has_lock_prefix @@ -1734,14 +1774,14 @@ def prove_direction(function): work.append(target) -def lift(pe, name, arguments=DEFAULT_ARGUMENTS, program=None, *, image_data=False): +def lift(pe, name, arguments=DEFAULT_ARGUMENTS, program=None, *, image_data=False, host_cpu=False): """Translate one export that takes the given number of integer arguments, 3 or 4. Functions it reaches through direct calls and tail jumps are translated into program.""" if not isinstance(arguments, int) or arguments not in ARGUMENT_COUNTS: raise ValueError(f"unsupported argument count {arguments!r} for export {name}: expected 3 or 4") entry = export_rva(pe, name) - program = program or Program(pe, image_data=image_data) + program = program or Program(pe, image_data=image_data, host_cpu=host_cpu) return program.lift(entry, f"lifted_{name}", ARGUMENT_REGISTERS[:arguments]) @@ -1771,9 +1811,10 @@ class Program: """The functions of one image reached from the requested exports through direct calls and tail jumps. Each callee is translated once, in internal mode, and its source precedes its callers'.""" - def __init__(self, pe, bindings=None, *, image_data=False, imports=None): + def __init__(self, pe, bindings=None, *, image_data=False, imports=None, host_cpu=False): self.pe = pe self.image_data = image_data + self.host_cpu = host_cpu self.imports = imports or {} self.entries = Entries(pe, bindings) self.active = [] @@ -1855,7 +1896,7 @@ def lift_function(program, entry, symbol, arguments, internal): "(an indirect jump through memory)") edges = function.explore(program.imports, import_resolver=program.import_resolver) image_data = program.image_data - lifter = Lifter(pe if image_data else None) + lifter = Lifter(pe if image_data else None, host_cpu=program.host_cpu) # A RIP-relative LEA that loads a recognised table base stays a guest address, with or without image data. bases = {(base, anchor) for *_, (_, _, base, anchor) in function.dispatches.values()} order = sorted(function.instructions) @@ -2058,9 +2099,11 @@ def lift_function(program, entry, symbol, arguments, internal): return "\n".join(source), function -PRELUDE = """#include +PRELUDE = """#include +#include #include #include +#include #include using word = std::uint64_t; static inline bool even_parity(word value) { @@ -2250,13 +2293,13 @@ def import_identities(pe): for desc in getattr(pe, "DIRECTORY_ENTRY_IMPORT", []) for imp in desc.imports} -def translate_pe(pe, names, bindings=None, *, image_data=False, binding=None): +def translate_pe(pe, names, bindings=None, *, image_data=False, binding=None, host_cpu=False): """binding is one Binding or a sequence of them; with several, each binds the IAT slot of the import it names.""" if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: raise ValueError("expected AMD64 PE32+") if image_data and {"bind_image", "unbind_image"} & {parse_entry(name)[0] for name in names}: raise ValueError("an export named bind_image or unbind_image collides with the image binding functions") - program = Program(pe, None if bindings is None else load_bindings(bindings), image_data=image_data) + program = Program(pe, None if bindings is None else load_bindings(bindings), image_data=image_data, host_cpu=host_cpu) bound = () if binding is None else (binding,) if isinstance(binding, Binding) else tuple(binding) for item in bound: if item.arguments not in IMPORT_ARGUMENT_COUNTS or item.return_bytes not in IMPORT_RETURN_WIDTHS: @@ -2367,9 +2410,9 @@ def parse_binding_options(options): return found[0] if len(found) == 1 else tuple(found) -def translate(image, names, bindings=None, *, image_data=False, binding=None): +def translate(image, names, bindings=None, *, image_data=False, binding=None, host_cpu=False): with pefile.PE(str(image), fast_load=True) as pe: - return translate_pe(pe, names, bindings, image_data=image_data, binding=binding) + return translate_pe(pe, names, bindings, image_data=image_data, binding=binding, host_cpu=host_cpu) if __name__ == "__main__": @@ -2378,6 +2421,8 @@ def translate(image, names, bindings=None, *, image_data=False, binding=None): parser.add_argument("exports", help='comma-separated export names; "name:4" translates that export with a ' "fourth integer argument in R9, and the host must pass four") parser.add_argument("output", type=Path) + parser.add_argument("--host-cpu", action="store_true", + help="opt into host-CPU instructions (rdfsbase, rdgsbase, wrfsbase, wrgsbase, rdpid)") parser.add_argument("--image-data", action="store_true", help="translate RIP-relative data against a live mapping of the image that the host " "binds at run time with lifted_bind_image; the generated source states the contract") @@ -2406,7 +2451,8 @@ def translate(image, names, bindings=None, *, image_data=False, binding=None): except ValueError as error: parser.error(str(error)) try: - source, functions = translate(args.image, args.exports.split(","), args.bind_ranges, image_data=args.image_data, binding=binding) + source, functions = translate(args.image, args.exports.split(","), args.bind_ranges, + image_data=args.image_data, binding=binding, host_cpu=args.host_cpu) args.output.write_text(source, encoding="utf-8") for function in functions: print(f"RVA {function.entry:#x}: {len(function.instructions)} instructions, " From 1a36111477d882c917162329ae884286c6a652db Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:45:05 +0100 Subject: [PATCH 055/775] d3d12_xs: stencil-less depth formats have no second read-only plane --- src/startup_stubs/d3d12_xs_device.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index b7651f9ce..2a485dbde 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1804,7 +1804,8 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO } dsv_format = view_format_of(resolved, dsv_target); const bool read_depth = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH) != 0; - const bool read_stencil = (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) != 0 || !format_has_stencil(dsv_format); + // A format without a stencil plane has no second plane to disagree with. + const bool read_stencil = !format_has_stencil(dsv_format) ? read_depth : (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL) != 0; if (read_depth != read_stencil) { if (first_calls(refused, 6)) log("x2w-d3d12 OMSetRenderTargets refused: depth stencil view with one read-only plane (flags 0x%x)", view.dsv_flags); return; From 1c3842a62ff140d904c48adb3997f48afa1272b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 14:43:56 +0300 Subject: [PATCH 056/775] startup: check the logical view table bounds src/startup_stubs/logical_view_table.h decides which part of the title's descriptor memory a translated draw may read through a root table handle. Its only end-to-end check, startup_logical_view_, skips (77) on an adapter that accepts the full oversized heap, which includes WARP. The other WARP draws bind a one-record table at offset 0. Single-point mutants of the header (inclusive end, no alignment check, no wrap guard, no below-heap check, off-by-one or ignored offset in record()) all left the WARP stream-consumer tests passing. startup_logical_view_table includes the header without a device and checks exact windows and records at the boundaries: first and last records, one past the end, misaligned and below-heap handles, missing heap fields, memory ending at and past UINT64_MAX, the 64-bit size product, and records crossing the end of a window. Each of those mutants now fails it. --- CMakeLists.txt | 6 ++ docs/startup-runtime.md | 6 +- tests/startup_logical_view_table_check.cpp | 103 +++++++++++++++++++++ 3 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 tests/startup_logical_view_table_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 820ccc686..7169fbe75 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -663,6 +663,12 @@ add_executable(startup_state_block_blend_check tests/startup_state_block_blend_c target_include_directories(startup_state_block_blend_check PRIVATE src) target_compile_features(startup_state_block_blend_check PRIVATE cxx_std_17) add_test(NAME startup_state_block_blend COMMAND startup_state_block_blend_check) +# Root table handles resolved against a logical view heap, and the records a translated draw reads +# from the window (src/startup_stubs/logical_view_table.h). +add_executable(startup_logical_view_table_check tests/startup_logical_view_table_check.cpp) +target_include_directories(startup_logical_view_table_check PRIVATE src) +target_compile_features(startup_logical_view_table_check PRIVATE cxx_std_17) +add_test(NAME startup_logical_view_table COMMAND startup_logical_view_table_check) # Colour-blend register decoding (src/startup_stubs/cb_blend.h, #1216): decoder table plus draws # compared with a CPU model of the register fields. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 75ef1d4b9..7a702f0c5 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -395,7 +395,11 @@ These are measured on one executable; treat them as hypotheses for others. an RTX 3060), so any failure of an oversized shader-visible view heap takes this path. The measured limits so far are 1,000,000 descriptors on both adapters. Reproduce with `ctest --preset release --no-tests=error -R '^startup_(view_heap|logical_view)_' -V`, which skips (77) on an - adapter that accepts the full request. + adapter that accepts the full request. WARP 10.0.26100.9818 and an RX 6600 (driver 32.0.21045.29003) + accept it, so those draws do not reach the table bounds there. `ctest --preset dev --no-tests=error -R '^startup_logical_view_table$' -V` checks + `src/startup_stubs/logical_view_table.h` without a device. It covers the first and last records, one + past the end, handles inside a record or below the heap, missing heap fields, memory that wraps past + the top of the address space, and records crossing the end of a window. - BCPack DirectStorage requests are decoded for BC7 and BC1 streams into destination memory as single atomic texture payloads; each request decompresses a complete multi-lane rANS chunk directly into its destination buffer and is excluded from chunk continuation caching. Unhandled formats fall back to zero-filled destinations. - The XG stand-in normally uses desktop copyable footprints. Its opt-in BC7 diagnostic reports standard GFX10 4 KiB tiled geometry for a single-slice, single-mip, non-MSAA diff --git a/tests/startup_logical_view_table_check.cpp b/tests/startup_logical_view_table_check.cpp new file mode 100644 index 000000000..9aa8c60d4 --- /dev/null +++ b/tests/startup_logical_view_table_check.cpp @@ -0,0 +1,103 @@ +// Checks src/startup_stubs/logical_view_table.h without a device: the window of the title's +// descriptor memory that a root table handle resolves to, and the records a draw may read from it. +#include "startup_stubs/logical_view_table.h" + +#include +#include +#include + +namespace { +using u64 = std::uint64_t; +int failures; + +void table(const char* name, u64 gpu, u64 cpu, unsigned count, unsigned stride, u64 handle, u64 address, u64 bytes) +{ + const x2w_startup::ViewTable got = x2w_startup::resolve_view_table(gpu, cpu, count, stride, handle); + if (got.address != address || got.bytes != bytes) { + std::printf("FAIL %s: address 0x%llx bytes 0x%llx, expected 0x%llx bytes 0x%llx\n", name, + static_cast(got.address), static_cast(got.bytes), + static_cast(address), static_cast(bytes)); + ++failures; + } +} + +void rejected(const char* name, u64 gpu, u64 cpu, unsigned count, unsigned stride, u64 handle) +{ + table(name, gpu, cpu, count, stride, handle, 0, 0); +} + +void record(const char* name, const x2w_startup::ViewTable& window, u64 offset, u64 size, u64 expected) +{ + const u64 got = window.record(offset, size); + if (got != expected) { + std::printf("FAIL %s: 0x%llx, expected 0x%llx\n", name, static_cast(got), + static_cast(expected)); + ++failures; + } +} +} // namespace + +int main() +{ + // A logical heap larger than the desktop limit, with the 32-byte records a translated draw reads. + constexpr u64 gpu = 0x10000000000, cpu = 0x20000000000; + constexpr unsigned count = 1245184, stride = 32; + constexpr u64 bytes = u64{count} * stride; + + // The window runs from the handle's record to the logical end. + table("first record", gpu, cpu, count, stride, gpu, cpu, bytes); + table("second record", gpu, cpu, count, stride, gpu + stride, cpu + stride, bytes - stride); + table("last record", gpu, cpu, count, stride, gpu + bytes - stride, cpu + bytes - stride, stride); + table("one record heap", gpu, cpu, 1, stride, gpu, cpu, stride); + table("stride 48", gpu, cpu, 4, 48, gpu + 96, cpu + 96, 96); + // The size is a 64-bit product of two 32-bit values. + constexpr u64 largest = u64{UINT_MAX} * UINT_MAX; + table("largest heap, last record", 0x1000, 0x2000, UINT_MAX, UINT_MAX, 0x1000 + largest - UINT_MAX, + 0x2000 + largest - UINT_MAX, UINT_MAX); + // Memory may end exactly at the top of the address space. + table("memory ending at UINT64_MAX", gpu, UINT64_MAX - bytes, count, stride, gpu, UINT64_MAX - bytes, bytes); + + // Handles outside the heap or between records give no window. + rejected("one past the last record", gpu, cpu, count, stride, gpu + bytes); + rejected("far past the last record", gpu, cpu, count, stride, gpu + 2 * bytes); + rejected("inside the second record", gpu, cpu, count, stride, gpu + stride + 8); + rejected("inside a stride 48 record", gpu, cpu, 4, 48, gpu + 64); + rejected("one record below the heap", gpu, cpu, count, stride, gpu - stride); + // Below the heap, even where the unsigned difference would land on a record. + rejected("below a heap at the top of the address space", UINT64_MAX - 63, cpu, 16, stride, 0xC0); + // Missing heap fields. + rejected("null GPU start", 0, cpu, count, stride, stride); + rejected("null CPU start", gpu, 0, count, stride, gpu); + rejected("zero stride", gpu, cpu, count, 0, gpu); + rejected("zero count", gpu, cpu, 0, stride, gpu); + // Memory that would wrap past the top of the address space. + rejected("memory ending past UINT64_MAX", gpu, UINT64_MAX - bytes + 1, count, stride, gpu); + rejected("largest heap past UINT64_MAX", 0x1000, UINT64_MAX - largest + 1, UINT_MAX, UINT_MAX, 0x1000); + + // Records inside a four-record window. + const x2w_startup::ViewTable window{cpu + stride, 4 * stride}; + record("first record", window, 0, stride, cpu + stride); + record("last record", window, 3 * stride, stride, cpu + 4 * stride); + record("whole window", window, 0, 4 * stride, cpu + stride); + record("record crossing the end", window, 3 * stride + 1, stride, 0); + record("record one byte too long", window, 3 * stride, stride + 1, 0); + record("window one byte too long", window, 0, 4 * stride + 1, 0); + record("record at the end", window, 4 * stride, stride, 0); + record("empty record past the end", window, 4 * stride + 1, 0, 0); + record("offset at UINT64_MAX", window, UINT64_MAX, stride, 0); + record("size at UINT64_MAX", window, 0, UINT64_MAX, 0); + // An unresolved table gives no record at any offset. + record("empty table, offset 0", x2w_startup::ViewTable{}, 0, stride, 0); + record("empty table, offset 64", x2w_startup::ViewTable{}, 2 * stride, stride, 0); + record("empty table, empty record", x2w_startup::ViewTable{}, 2 * stride, 0, 0); + + // Through both: the final logical record, and nothing beyond it. + const auto last = x2w_startup::resolve_view_table(gpu, cpu, count, stride, gpu + bytes - stride); + record("last logical record", last, 0, stride, cpu + bytes - stride); + record("past the last logical record", last, stride, stride, 0); + record("last logical record, one byte too long", last, 0, stride + 1, 0); + + if (failures) return 1; + std::printf("logical view table: windows and records exact\n"); + return 0; +} From 5a71e68213daab4f5d028abbbf4995841547a5a5 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:45:36 +0100 Subject: [PATCH 057/775] docs: state what the device run verified for the new plane-size formats --- docs/startup-runtime.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index dd69e7470..08c4e1678 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -614,10 +614,11 @@ B8G8R8A8/B8G8R8X8 (87-93) families. Both allocation-info entries (slots 25 and 1 answer for them. Verification status: the device-independent reference sizes in `tests/startup_plane_size_check.cpp` -(`startup_plane_size`) cover R24G8 and the added colour families. The R24G8 and added MSAA colour -formats have not yet been verified through the Windows device wrapper -(`startup_plane_size_device_`, reproduced with the second command below); only the fixture result -is established for them. +(`startup_plane_size`) cover R24G8 and the added colour families. `startup_plane_size_device_` +checks that the wrapper answers the helper's result for the adapter's own desktop answer; it passed +on Windows Server 2025 (WARP and the hardware case) in Debug and Release. It does not show that the +console layout fits the answered size for these formats; no console reference sizes are listed for +R24G8 or the added colour families. - `ctest --preset release --no-tests=error -R '^startup_plane_size(_packed_control)?$' -V` checks the rule without a device, including the shapes it refuses. From e75048628440ab801ffab7ec63d27f63ab4a47b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 14:45:24 +0300 Subject: [PATCH 058/775] textures: check the BC7 4 KiB standard detile order src/startup_stubs/bc7_4k_s.h was reached only through the XG layout check and the BC7 draw checks. Those run 81x69 and 64x64 surfaces, whose tile grids are square (2x2 and 1x1), and pass only accepted descriptions. A block offset that multiplied the tile row by the tile row count instead of the tile column count, or a supports_bc7_4k_s that dropped the MipLevels or Alignment condition, passed every existing CPU and WARP test. The draw check tiles and detiles with the same block offsets, so it cannot see a wrong bit order on its own. startup_bc7_4k_s builds against the header alone. It compares every block offset with a table of the documented y0 y1 x0 x1 y2 x2 y3 x3 bits and with hand-worked offsets on partial and non-square grids (200x72, 72x200). It checks the padded sizes from 1x1 to 16384x16384 and detile into destinations at three row pitches with guard bytes. It also refuses 24 descriptions, each with one field changed. The x-first control expects the wrong order and must fail. --- CMakeLists.txt | 8 + docs/startup-runtime.md | 8 + tests/startup_bc7_4k_s_check.cpp | 263 +++++++++++++++++++++++++++++++ 3 files changed, 279 insertions(+) create mode 100644 tests/startup_bc7_4k_s_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 820ccc686..af5fe483a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -646,6 +646,14 @@ foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_plane_size_device_${adapter} COMMAND startup_plane_size_device_check ${adapter}) endforeach() set_tests_properties(startup_plane_size_device_hardware PROPERTIES SKIP_RETURN_CODE 77) +# Opt-in BC7 4 KiB standard surfaces (src/startup_stubs/bc7_4k_s.h): accepted descriptions, padded +# sizes, block order and detile; the mutated run (x-first bit order) is the negative control. +add_executable(startup_bc7_4k_s_check tests/startup_bc7_4k_s_check.cpp) +target_include_directories(startup_bc7_4k_s_check PRIVATE src) +target_compile_features(startup_bc7_4k_s_check PRIVATE cxx_std_17) +add_test(NAME startup_bc7_4k_s COMMAND startup_bc7_4k_s_check) +add_test(NAME startup_bc7_4k_s_x_first_control COMMAND startup_bc7_4k_s_check --mutate x-first) +set_tests_properties(startup_bc7_4k_s_x_first_control PROPERTIES WILL_FAIL TRUE) # Descriptor heaps whose desktop CPU start is not an address get plain memory as the start the # executable sees (src/startup_stubs/title_heap_memory.h); the mutated run is the negative control. add_executable(startup_title_heap_check tests/startup_title_heap_check.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 75ef1d4b9..755a62157 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -407,6 +407,14 @@ These are measured on one executable; treat them as hypotheses for others. stand-in must be loaded for render-mode copies. The reported pitch describes the padded block-row extent of the surface. Synthetic copy and draw checks run with `ctest --preset dev --no-tests=error -R '^startup_xg_bc7_' -V`. + Those checks use only accepted descriptions at 81x69 and 64x64 (square 2x2 and 1x1 tile grids), + and the draw check tiles and detiles with the same block offsets. `tests/startup_bc7_4k_s_check.cpp` + covers `src/startup_stubs/bc7_4k_s.h` without a device. It compares every block offset with the + documented bit order on partial and non-square tile grids (200x72 is 4x2 tiles). It checks the + padded sizes from 1x1 to 16384x16384 and detile at three row pitches with guard bytes. It also + refuses each description with one field changed, such as two mips or 4 KiB alignment. Run + `ctest --preset dev --no-tests=error -R '^startup_bc7_4k_s' -V`; the `_x_first_control` run + checks an x-first order and must fail. - The default translator uses a static default sampler for a dynamically indexed sampler-heap load. With the sampler-heap opt-in, translated draws snapshot the bound heap's 16-byte sampler entries and bind a private desktop table beside the static samplers. Missing, out-of-range, or unreadable entries diff --git a/tests/startup_bc7_4k_s_check.cpp b/tests/startup_bc7_4k_s_check.cpp new file mode 100644 index 000000000..ebf338829 --- /dev/null +++ b/tests/startup_bc7_4k_s_check.cpp @@ -0,0 +1,263 @@ +// Checks src/startup_stubs/bc7_4k_s.h without a device: the descriptions supports_bc7_4k_s accepts +// and refuses, Bc16Surface's padded sizes, every block offset on surfaces with partial and +// non-square tile grids, and detile into a pitched destination with guard bytes. +// +// The expected offsets come from the documented bit order, written as a table of (axis, bit) +// pairs, and from literal offsets worked out by hand; neither reuses the header's shifts and masks. +#include "startup_stubs/bc7_4k_s.h" + +#include +#include +#include +#include + +namespace { +int failures; + +using x2w_startup::Bc16Surface; + +struct Bit { + char axis; + unsigned bit; +}; + +// Block index bits from low to high: y0 y1 x0 x1 y2 x2 y3 x3. +constexpr Bit documented[8] = {{'y', 0}, {'y', 1}, {'x', 0}, {'x', 1}, {'y', 2}, {'x', 2}, {'y', 3}, {'x', 3}}; +// --mutate x-first: a plain x-first Morton order (negative control: the check must then fail). +constexpr Bit x_first[8] = {{'x', 0}, {'y', 0}, {'x', 1}, {'y', 1}, {'x', 2}, {'y', 2}, {'x', 3}, {'y', 3}}; +const Bit* order = documented; + +std::uint64_t expected_offset(UINT column, UINT row, UINT columns) +{ + const UINT tile_columns = (columns + 15) / 16; + const UINT x = column % 16, y = row % 16; + UINT block = 0; + for (UINT position = 0; position < 8; ++position) + block |= (((order[position].axis == 'x' ? x : y) >> order[position].bit) & 1u) << position; + return (std::uint64_t{row / 16} * tile_columns + column / 16) * 4096 + block * 16; +} + +void fail(const char* name, const char* format, ...) +{ + std::printf("FAIL %s: ", name); + va_list args; + va_start(args, format); + std::vprintf(format, args); + va_end(args); + std::printf("\n"); + ++failures; +} + +unsigned long long u64(std::uint64_t value) { return value; } + +void block_tag(unsigned char* out, UINT x, UINT y) +{ + out[0] = static_cast(x); + out[1] = static_cast(x >> 8); + out[2] = static_cast(y); + out[3] = static_cast(y >> 8); + for (UINT i = 4; i < 16; ++i) out[i] = static_cast(0x40 + i + x * 3 + y * 5); +} + +// Sizes, every block offset, and detile through padded row pitches with guards on both ends. +void surface(const char* name, UINT width, UINT height, UINT columns, UINT rows, UINT padded_width, + UINT padded_height, UINT row_bytes, std::uint64_t size, bool full = true) +{ + const int before = failures; + const Bc16Surface s(width, height); + if (s.columns != columns || s.rows != rows) fail(name, "blocks %ux%u, expected %ux%u", s.columns, s.rows, columns, rows); + if (s.padded_width() != padded_width || s.padded_height() != padded_height) + fail(name, "padded %ux%u, expected %ux%u", s.padded_width(), s.padded_height(), padded_width, padded_height); + if (s.padded_row_bytes() != row_bytes) fail(name, "padded row bytes %u, expected %u", s.padded_row_bytes(), row_bytes); + if (s.size() != size) fail(name, "size %llu, expected %llu", u64(s.size()), u64(size)); + if (!full || failures != before) return; + + std::vector seen(static_cast(size / 16)); + for (UINT y = 0; y < rows; ++y) + for (UINT x = 0; x < columns; ++x) { + const auto offset = s.block_offset(x, y), want = expected_offset(x, y, columns); + if (offset != want) { + fail(name, "block (%u, %u) at 0x%llx, expected 0x%llx", x, y, u64(offset), u64(want)); + return; + } + if (offset + 16 > size || seen[static_cast(offset / 16)]++) { + fail(name, "block (%u, %u) outside the surface or reused at 0x%llx", x, y, u64(offset)); + return; + } + } + + // Tiled source: caller padding 0xff, each visible block tagged with its own coordinates. + std::vector tiled(static_cast(size), 0xff); + for (UINT y = 0; y < rows; ++y) + for (UINT x = 0; x < columns; ++x) + block_tag(&tiled[static_cast(expected_offset(x, y, columns))], x, y); + const auto source = tiled; + + for (UINT extra : {0u, 48u, 256u}) { + const UINT pitch = columns * 16 + extra; + const std::size_t guard = 64, span = std::size_t{rows - 1} * pitch + columns * 16; + std::vector dest(guard + std::size_t{rows} * pitch + guard, 0xa5); + s.detile(tiled.data(), dest.data() + guard, pitch); + if (tiled != source) fail(name, "detile wrote its source (pitch %u)", pitch); + for (std::size_t i = 0; i < dest.size(); ++i) { + const bool inside = i >= guard && i < guard + span && (i - guard) % pitch < columns * 16; + if (inside) { + const std::size_t at = i - guard; + const UINT y = static_cast(at / pitch), x = static_cast(at % pitch / 16); + unsigned char want[16]; + block_tag(want, x, y); + if (dest[i] != want[at % 16]) { + fail(name, "detile pitch %u: block (%u, %u) wrong", pitch, x, y); + break; + } + } else if (dest[i] != 0xa5) { + fail(name, "detile pitch %u wrote a guard or row-gap byte at %lld", pitch, + static_cast(i) - static_cast(guard)); + break; + } + } + } +} + +void offset(const char* name, UINT width, UINT height, UINT column, UINT row, std::uint64_t want) +{ + const auto got = Bc16Surface(width, height).block_offset(column, row); + if (got != want) fail(name, "0x%llx, expected 0x%llx", u64(got), u64(want)); +} + +D3D12_RESOURCE_DESC bc7(UINT64 width = 81, UINT height = 69) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_BC7_UNORM; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + return desc; +} + +void accepted(const char* name, const D3D12_RESOURCE_DESC& desc, bool want) +{ + if (x2w_startup::supports_bc7_4k_s(desc) != want) fail(name, want ? "refused, expected accepted" : "accepted, expected refused"); +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "x-first") == 0) order = x_first; + + // Hand-worked offsets: each bit of the order alone, then the tile index on 4-by-2 and 2-by-4 + // tile grids (200x72 and 72x200), where a row-major index using the tile row count would differ. + offset("block (0, 1): y0", 64, 64, 0, 1, 0x10); + offset("block (0, 2): y1", 64, 64, 0, 2, 0x20); + offset("block (1, 0): x0", 64, 64, 1, 0, 0x40); + offset("block (2, 0): x1", 64, 64, 2, 0, 0x80); + offset("block (0, 4): y2", 64, 64, 0, 4, 0x100); + offset("block (4, 0): x2", 64, 64, 4, 0, 0x200); + offset("block (0, 8): y3", 64, 64, 0, 8, 0x400); + offset("block (8, 0): x3", 64, 64, 8, 0, 0x800); + offset("block (15, 15)", 64, 64, 15, 15, 0xff0); + offset("block (5, 3)", 64, 64, 5, 3, 0x270); + offset("200x72 block (16, 0): tile 1", 200, 72, 16, 0, 0x1000); + offset("200x72 block (0, 16): tile 4", 200, 72, 0, 16, 0x4000); + offset("200x72 block (49, 17): tile 7", 200, 72, 49, 17, 0x7050); + offset("72x200 block (0, 16): tile 2", 72, 200, 0, 16, 0x2000); + offset("72x200 block (17, 49): tile 7", 72, 200, 17, 49, 0x7050); + offset("16384x16384 last block", 16384, 16384, 4095, 4095, 0xffffff0ull); + + // name, pixels, blocks, padded pixels, padded row bytes, size. + surface("1x1", 1, 1, 1, 1, 64, 64, 256, 4096); + surface("4x4", 4, 4, 1, 1, 64, 64, 256, 4096); + surface("5x3", 5, 3, 2, 1, 64, 64, 256, 4096); + surface("64x64", 64, 64, 16, 16, 64, 64, 256, 4096); + surface("65x64", 65, 64, 17, 16, 128, 64, 512, 8192); + surface("64x65", 64, 65, 16, 17, 64, 128, 256, 8192); + surface("81x69", 81, 69, 21, 18, 128, 128, 512, 16384); + surface("200x72", 200, 72, 50, 18, 256, 128, 1024, 32768); + surface("72x200", 72, 200, 18, 50, 128, 256, 512, 32768); + surface("16384x16384", 16384, 16384, 4096, 4096, 16384, 16384, 65536, 0x10000000ull, false); + + // The description constructor reads the same width and height. + const Bc16Surface from_desc(bc7(200, 72)); + if (from_desc.columns != 50 || from_desc.rows != 18 || from_desc.tile_columns != 4 || from_desc.tile_rows != 2) + fail("Bc16Surface(desc) 200x72", "%ux%u blocks, %ux%u tiles", from_desc.columns, from_desc.rows, + from_desc.tile_columns, from_desc.tile_rows); + + // Accepted: one 2D BC7_UNORM top mip in the default layout, at both dimension limits. + accepted("81x69", bc7(), true); + accepted("1x1", bc7(1, 1), true); + accepted("16384x16384", bc7(16384, 16384), true); + // Refused: one field changed at a time. + auto desc = bc7(); + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + accepted("3D", desc, false); + desc = bc7(); + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; + accepted("1D", desc, false); + desc = bc7(); + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + accepted("buffer", desc, false); + desc = bc7(); + desc.Format = DXGI_FORMAT_BC7_UNORM_SRGB; + accepted("BC7_UNORM_SRGB", desc, false); + desc = bc7(); + desc.Format = DXGI_FORMAT_BC7_TYPELESS; + accepted("BC7_TYPELESS", desc, false); + desc = bc7(); + desc.Format = DXGI_FORMAT_BC3_UNORM; + accepted("BC3_UNORM", desc, false); + desc = bc7(); + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + accepted("row-major layout", desc, false); + desc = bc7(); + desc.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + accepted("64 KiB swizzle layout", desc, false); + accepted("width 0", bc7(0, 69), false); + accepted("width 16385", bc7(16385, 69), false); + accepted("width 2^32 + 64 (64 once truncated)", bc7(0x100000040ull, 69), false); + accepted("height 0", bc7(81, 0), false); + accepted("height 16385", bc7(81, 16385), false); + desc = bc7(); + desc.DepthOrArraySize = 0; + accepted("zero slices", desc, false); + desc = bc7(); + desc.DepthOrArraySize = 2; + accepted("two slices", desc, false); + desc = bc7(); + desc.MipLevels = 0; + accepted("full mip chain (MipLevels 0)", desc, false); + desc = bc7(); + desc.MipLevels = 2; + accepted("two mips", desc, false); + desc = bc7(); + desc.SampleDesc.Count = 0; + accepted("zero samples", desc, false); + desc = bc7(); + desc.SampleDesc.Count = 4; + accepted("four samples", desc, false); + desc = bc7(); + desc.SampleDesc.Quality = 1; + accepted("sample quality 1", desc, false); + desc = bc7(); + desc.Alignment = 0x1000; + accepted("4 KiB alignment", desc, false); + desc = bc7(); + desc.Alignment = 0x10000; + accepted("64 KiB alignment", desc, false); + desc = bc7(); + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + accepted("unordered-access flag", desc, false); + desc = bc7(); + desc.Flags = D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; + accepted("deny-shader-resource flag", desc, false); + + if (failures) { + std::printf("startup_bc7_4k_s: %d FAILED\n", failures); + return 1; + } + std::printf("startup_bc7_4k_s: PASS (16 offsets, 10 surfaces, 3 accepted, 24 refused descriptions)\n"); + return 0; +} From 22458aea02b54b5b6ac040a63881aa7ae8dda1d6 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 17:15:49 +0800 Subject: [PATCH 059/775] shader: lower gfx1030 fixed-address atomic counters --- CMakeLists.txt | 7 +++++ README.md | 1 + docs/experiments.md | 23 +++++++++++++++ tests/compute_store_check.py | 56 ++++++++++++++++++++++++++++++++++++ tools/compute_store_aot.py | 18 ++++++++++-- 5 files changed, 103 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8acd8f3e7..ffb1b21f8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5481,6 +5481,13 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(compute_store_aot_mubuf_${exchange}_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_${exchange}_${adapter}.txt") endforeach() + foreach(counter IN ITEMS counter counter-x2) + add_test(NAME compute_store_aot_mubuf_${counter}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" "draw-mubuf-${counter}" "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_mubuf_${counter}_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_${counter}_${adapter}.txt") + endforeach() add_test(NAME compute_store_aot_mubuf_vector_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mubuf-vector "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index b4f7eb62b..d50489001 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 raw subword reads | Lower [indexed byte and halfword MUBUF loads](docs/experiments.md#indexed-gfx1030-raw-subword-reads) and compare sign and zero extension in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_subword_'` | | gfx1030 64-bit atomic buffer reductions | Lower [fixed-address MUBUF integer `_x2` reductions](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-x2-reductions) with SM 6.6 raw UAV atomics. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_reduction_x2_'` | | gfx1030 atomic buffer exchanges | Lower [fixed-address MUBUF integer swap and compare-swap](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-exchanges) for 32 and 64 bits. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_exchange'` | +| gfx1030 atomic buffer counters | Lower [fixed-address MUBUF bounded increment and decrement](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-counters) for 32 and 64 bits. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_counter'` | | gfx1030 atomic buffer reductions | Lower [fixed-address MUBUF integer reductions](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-reductions) and verify the final value under lane contention. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_reduction_'` | | gfx1030 raw vector reads | Lower [indexed `buffer_load_dwordx2/x3/x4`](docs/experiments.md#indexed-gfx1030-raw-vector-reads) and verify channel order, destination/index aliasing and untouched output. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_vector_'` | | gfx1030 image loads | Lower [typed RGBA32 and packed RGBA8 2D reads](docs/experiments.md#gfx1030-2d-image-loads), including explicit mip levels, with 32-bit or `a16` addresses and nonzero `dmask` values. Compare the UAV readback against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_(load|mip|packed)_'` | diff --git a/docs/experiments.md b/docs/experiments.md index eb780b857..03d87652c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3720,6 +3720,29 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_exchange' -V ``` +### gfx1030 fixed-address MUBUF atomic counters + +The compute store profile lowers `buffer_atomic_inc`, `buffer_atomic_dec` +and their `_x2` forms with `glc` clear. The +[AMD RDNA 2 Shader ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) +defines increment as wrapping to zero at or above the unsigned limit. +Decrement wraps to the limit from zero or from above the limit. The HLSL +compares and exchanges the candidate word or pair and retries with the +observed value if another lane has updated it. The fixed-address and +sole-UAV-access rules apply. Compile `_x2` with `cs_6_6`. + +One and two wave32 groups contend on the same counter with an identical +limit. The initial value exceeds the limit. The 32-bit fixture wraps +several times, and the 64-bit decrement crosses a DWORD boundary. Both +sizes compare all 320 words with a CPU reference. A shader that omits the +retry must fail at word 2. The LLVM 15 test checks assembly and the +compute-container CLI. The GPU fixtures execute translated DXIL. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_counter' -V +``` + ### Indexed gfx1030 raw vector reads The compute store profile also lowers `buffer_load_dwordx2`, diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index ee8ff1177..a4813eaec 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -3253,6 +3253,59 @@ def mubuf_exchange_draw(directory, compiler, renderer, backend, wide=False): return 0 +def mubuf_counter_cases(wide=False): + for op in ("inc", "dec"): + name = f"buffer_atomic_{op}{'_x2' if wide else ''}" + data = "v[10:11]" if wide else "v10" + lines = ["s_mov_b32 s12, s7", "s_mov_b32 s13, 0", + "s_load_dwordx4 s[20:23], s[12:13], 0x30", "s_waitcnt lgkmcnt(0)", + "v_mov_b32_e32 v10, 8"] + if wide: + lines += ["v_mov_b32_e32 v11, 1"] + lines += [f"{name} {data}, off, s[20:23], 0 offset:8", "s_endpgm"] + yield name, lines, {k: v for k, v in DS_BINDING.items() if k != "stride"} + + +def mubuf_counter_draw(directory, compiler, renderer, backend, wide=False): + src, cso, case = (directory / f"mubuf-counter.{ext}" for ext in ("hlsl", "cso", "case")) + compile_shader = [compiler, "-T", "cs_6_6" if wide else "cs_6_0", "-E", "main", "-Fo", cso, src] + runner = "--compute-store-case-atomic64" if wide else "--compute-store-case" + run = [renderer, backend, runner, cso, case] + accepted = [] + for name, lines, binding in mubuf_counter_cases(wide): + print(name, flush=True) + kernel = aot.lower(lines, 32, **binding) + src.write_text(kernel, encoding="ascii") + subprocess.run(compile_shader, check=True) + for groups in (1, 2): + words = [SENTINEL] * 320 + # The first operation moves the above-limit sentinel to the start of the cycle. + limit = (1 << 32) + 8 if wide else 8 + remaining = (32 * groups - 1) % (limit + 1) + value = remaining if "_inc" in name else limit - remaining + words[2] = value & 0xffffffff + if wide: + words[3] = value >> 32 + case.write_bytes(struct.pack("<321I", groups, *words)) + result = subprocess.run(run) + if result.returncode: + return result.returncode + mutant = kernel.replace("while (observed != expected)", "while (false)") + assert mutant != kernel + src.write_text(mutant, encoding="ascii") + subprocess.run(compile_shader, check=True) + bad = subprocess.run(run, capture_output=True, text=True) + if bad.returncode != 1 or f"word=2 expected={words[2]:08x} actual={SENTINEL:08x}" not in bad.stderr: + raise AssertionError(f"{name}: missing CAS retry escaped detection\n{bad.stderr}") + print(bad.stderr, end="") + accepted.append(name) + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(accepted) + "\n", encoding="utf-8") + return 0 + + def scalar_alu_binary(directory, assembler, objcopy, library): """The assembled scalar chain decodes to the same program as its text.""" src, obj, raw = [directory / x for x in ("scalar.s", "scalar.o", "scalar.bin")] @@ -3310,6 +3363,7 @@ def binary(directory, assembler, objcopy, library): gfx1030_binary(directory, assembler, objcopy, library, mubuf_reduction_cases(wide), "buffer_atomic_") mubuf_exchange_controls(wide) gfx1030_binary(directory, assembler, objcopy, library, mubuf_exchange_cases(wide), "buffer_atomic_") + gfx1030_binary(directory, assembler, objcopy, library, mubuf_counter_cases(wide), "buffer_atomic_") mubuf_subword_controls() gfx1030_binary(directory, assembler, objcopy, library, mubuf_subword_cases(), "buffer_load_") mubuf_vector_controls() @@ -5458,6 +5512,8 @@ def draw(directory, compiler, renderer, backend, cases=None): modes = {"binary": binary, "draw": draw, "draw-mubuf-subword": mubuf_subword_draw, "draw-mubuf-reduction": mubuf_reduction_draw, + "draw-mubuf-counter": mubuf_counter_draw, + "draw-mubuf-counter-x2": lambda d, *a: mubuf_counter_draw(d, *a, wide=True), "draw-mubuf-exchange": mubuf_exchange_draw, "draw-mubuf-exchange-x2": lambda d, *a: mubuf_exchange_draw(d, *a, wide=True), "draw-mubuf-reduction-x2": lambda d, *a: mubuf_reduction_draw(d, *a, wide=True), diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index e28130767..6295491cf 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -97,6 +97,7 @@ "add": "Add", "sub": "Add", "and": "And", "or": "Or", "xor": "Xor", "smin": "Min", "umin": "Min", "smax": "Max", "umax": "Max", "swap": "Exchange", "cmpswap": "CompareExchange", + "inc": "CompareExchange", "dec": "CompareExchange", } @@ -1308,8 +1309,21 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if op == "cmpswap": # The ISA places replacement before compare, unlike the HLSL argument order. word = f"{operands[1]}, {word}" - stores.extend((f" {kind} ignoredAtomic;", - f" outputData.Interlocked{method}({offset}u, {word}, ignoredAtomic);")) + if op in ("inc", "dec"): + one, zero = ("1ull", "0ull") if wide else ("1u", "0u") + if op == "inc": + desired = f"expected >= limit ? {zero} : expected + {one}" + else: + desired = f"expected == {zero} || expected > limit ? limit : expected - {one}" + # Seed the first compare with zero. A failed CAS returns the word for the next try. + stores.extend((f" const {kind} limit = {word};", f" {kind} observed = {zero};", + f" {kind} expected;", " [allow_uav_condition] do {", + " expected = observed;", f" {kind} next = {desired};", + f" outputData.Interlocked{method}({offset}u, expected, next, observed);", + " } while (observed != expected);")) + else: + stores.extend((f" {kind} ignoredAtomic;", + f" outputData.Interlocked{method}({offset}u, {word}, ignoredAtomic);")) atomic_update = True elif m := re.fullmatch(r"(?:buffer_store_(?:dword(?:x(?P[234]))?|(?Pbyte|short)(?P_d16_hi)?)|" r"(?Pt)?buffer_store_format_(?P(?:d16_)?(?:x|xy|xyz|xyzw))) " From 5dfcb3c653cc0c0f126e78cc2eb3cd7fcd1c75ba Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 19:32:11 +0800 Subject: [PATCH 060/775] shader: lower experimental gfx1030 packed D16 XYZ stores --- CMakeLists.txt | 4 + README.md | 2 +- docs/experiments.md | 56 +++++++--- tests/compute_store_check.py | 57 ++++++++-- tests/gfx1030_mubuf_d16/build.sh | 27 +++++ tests/gfx1030_mubuf_d16/check.py | 152 ++++++++++++++++++++++++++ tests/gfx1030_mubuf_d16/d16-gfx1100.s | 66 +++++++++++ tests/gfx1030_mubuf_d16/d16.s | 66 +++++++++++ tools/compute_store_aot.py | 19 +++- 9 files changed, 416 insertions(+), 33 deletions(-) create mode 100644 tests/gfx1030_mubuf_d16/build.sh create mode 100644 tests/gfx1030_mubuf_d16/check.py create mode 100644 tests/gfx1030_mubuf_d16/d16-gfx1100.s create mode 100644 tests/gfx1030_mubuf_d16/d16.s diff --git a/CMakeLists.txt b/CMakeLists.txt index 8acd8f3e7..c942d9d37 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5585,6 +5585,10 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mubuf_store_format_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_store_format_${adapter}.txt") + add_test(NAME compute_store_aot_mubuf_store_format_xyz_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mubuf-format-store-xyz "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_mubuf_store_format_xyz_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) add_test(NAME compute_store_aot_mtbuf_store_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mtbuf-store "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index b4f7eb62b..339da65cd 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 formatted D16 UINT reads | Lower [indexed `buffer_load_format_d16_*` with caller-declared RGBA16 UINT](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-reads) and verify packed channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_load_format_d16_'` | | gfx1030 raw D16 reads | Lower [indexed D16 byte and short MUBUF loads](docs/experiments.md#indexed-gfx1030-raw-d16-reads) and verify that the other VGPR half stays unchanged. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_d16_'` | | gfx1030 formatted UINT buffer reads | Lower [indexed `buffer_load_format_*` with caller-declared RGBA32 UINT](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-reads) and verify one to four channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_format_'` | -| gfx1030 formatted D16 UINT writes | Lower [indexed packed `buffer_store_format_d16_x/xy/xyzw`](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-writes) and verify the untouched halfword and record padding. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | +| gfx1030 formatted D16 UINT writes | Lower [indexed packed `buffer_store_format_d16_x/xy/xyzw`](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-writes) and verify the untouched halfword and record padding. The experimental `xyz` form requires a caller-verified W-preservation contract. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | gfx1030 formatted UINT buffer writes | Lower [indexed `buffer_store_format_*` with matching caller-declared UINT texels](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-writes) and compare full UAV readback with a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | Shader census | [Distinguish archive records, header digests and cache-index entries](docs/experiments.md#reporting-shader-census-populations) before choosing a coverage denominator. | `ctest --preset dev --no-tests=error -R "^shader_metadata_census$" -V` | | Shader effect metadata | Inventory the [candidate programs for a named SGD5 effect](docs/experiments.md#candidate-programs-for-a-named-sgd5-effect) using independently located archive ranges. | `ctest --preset dev --no-tests=error -R "^sgd5_effect_candidates$" -V` | diff --git a/docs/experiments.md b/docs/experiments.md index eb780b857..1ed5f904c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3921,23 +3921,29 @@ The compute store profile accepts `buffer_store_format_d16_x`, `_xy` and `BUF_FMT_16_16_16_16_UINT`, respectively. The caller declares the format and identity destination selectors. The [AMD RDNA 2 Shader ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) (§8.1.4 and MUBUF opcodes 132–135) sends packed 16-bit channels to the -texture unit, low half first. The profile requires a whole texel. The ISA -format table has no three-channel 16-bit UINT format, and the `xyz` form -with a four-channel descriptor still needs a native fourth-channel check. - -The D16 forms use the same verified `idxen`, zero scalar offset, -DWORD alignment and record bounds as the ordinary UINT forms. For `x`, -the raw UAV lowering reserves the containing DWORD and preserves its high -half with a read/modify/write. The caller supplies an in-range, exclusively -owned DWORD even though the original instruction writes two bytes. The -translator refuses any store that overlaps that DWORD, including an -otherwise disjoint halfword write. - -The shared formatted store fixture compares all 320 output words on -WARP and a physical adapter at one and two groups. The CPU reference copies -selected bytes into the initial output. Clearing the preserved half for -`x` or swapping the first two channels for `xy` and `xyzw` must produce a -difference at word 1. LLVM 15 also exercises each encoding through the +texture unit, low half first. The default profile accepts whole texels. + +An experimental `--mubuf-d16-xyz-mode preserve-w` contract allows +`buffer_store_format_d16_xyz` with `--output-format BUF_FMT_16_16_16_16_UINT`. +The caller verifies that the original instruction with this descriptor keeps +W unchanged. The lowering writes XY and replaces the low half of the next +DWORD with Z. The candidate requires native gfx1030 readback with distinct +initial W and input W values before it is counted in form coverage. + +All D16 forms require `idxen`, zero scalar offset, DWORD alignment and a +verified record layout. The raw UAV lowering for `x` and the experimental +`xyz` form reserves the entire containing DWORD for each partial write. The +caller supplies an in-range record and exclusive ownership of each DWORD +across invocations. The translator refuses overlapping stores, including an +otherwise disjoint halfword write within the preserved DWORD. + +The formatted store fixtures compare all 320 output words on WARP and a +physical adapter at one and two groups. The CPU reference copies selected +bytes into the initial output. Clearing the preserved half for `x` or +swapping the first two channels for `xy` and `xyzw` must produce a difference +at word 1. The separate `xyz` fixture replaces the instruction with `xyzw` +and requires the first difference at word 2, expected `c5c54567`, actual +`01234567`. LLVM 15 exercises all these encodings through the synthetic compute-container CLI. ```powershell @@ -3949,6 +3955,22 @@ ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_' python3 -B tests/compute_store_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 ``` +For independent native readback on Linux, select a gfx1030 device in +`rocminfo`. Build the source fixture with LLVM and LLD 15, then launch +it through HIP: + +```sh +sh tests/gfx1030_mubuf_d16/build.sh gfx1030 +python3 -B tests/gfx1030_mubuf_d16/check.py --target gfx1030 --device 0 +``` + +The fixture checks 448 halfwords at one, two and three workgroups. Its +XYZW control overwrites W with `ca5e`, where the XYZ reference preserves +`8103` in the first record. The out-of-bounds control first differs at +halfword 256 (`8200` preserved versus `1317` written). Use `--model-only` +for the CPU reference and controls. The optional `gfx1100` target uses +its own descriptor encoding and provides a separate RDNA 3 comparison. + ### Per-lane guards around compute stores A per-lane bound such as `if (gid < n) store` compiles under LLVM 15 to one exit, with no early `s_endpgm`. A `v_cmp` sets `vcc_lo`, `s_and_saveexec_b32` saves `exec_lo` and masks it, and an optional `s_cbranch_execz` skips the masked block when no lane passes. `s_or_b32 exec_lo, exec_lo, sN` then restores the mask, or the program exits with the mask still applied. The store profile lowers this form as control flow: the stores issued under the mask go inside an HLSL `if`, and stores after the restore stay outside it. diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index ee8ff1177..ec53894d4 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -3347,6 +3347,8 @@ def binary(directory, assembler, objcopy, library): two_exits(directory, assembler, objcopy, library) mubuf_format_store_controls() mubuf_format_d16_store_controls() + gfx1030_binary(directory, assembler, objcopy, library, mubuf_format_store_cases(xyz=True), + "buffer_store_format_d16_", group=16) for packed in (False, True): gfx1030_binary(directory, assembler, objcopy, library, mubuf_format_store_cases(packed), "buffer_store_format_", group=16) @@ -4004,8 +4006,12 @@ def mubuf_format_draw(directory, compiler, renderer, backend): MUBUF_STORE_WORDS = (0x89abcdef, 0x01234567, 0xdcbafed0, 0x76543210) -def mubuf_format_store_cases(packed=False): - for components in ((1, 2, 4) if packed else range(1, 5)): +def mubuf_format_store_cases(packed=False, *, xyz=False): + if xyz: + packed, widths = True, (3,) + else: + widths = (1, 2, 4) if packed else range(1, 5) + for components in widths: name = f"buffer_store_format_{'d16_' if packed else ''}{'xyzw'[:components]}" count = (components + 1) // 2 if packed else components component_format = "16_" if packed else "32_" @@ -4014,8 +4020,12 @@ def mubuf_format_store_cases(packed=False): "s_load_dwordx4 s[20:23], s[12:13], 0x30", "v_lshl_add_u32 v8, s11, 4, v0", "s_waitcnt lgkmcnt(0)"] lines += [f"v_xor_b32_e32 v{10 + i}, {word:#x}, v8" for i, word in enumerate(MUBUF_STORE_WORDS[:count])] - yield name, [*lines, f"{name} {data}, v8, s[20:23], 0 idxen offset:4", "s_endpgm"], DS_BINDING | { - "stride": 4 * (count + 1), "output_format": f"BUF_FMT_{component_format * components}UINT"} + format_components = 4 if xyz else components + binding = DS_BINDING | {"stride": 4 * (count + 1), + "output_format": f"BUF_FMT_{component_format * format_components}UINT"} + if xyz: + binding["mubuf_d16_xyz_mode"] = "preserve-w" + yield name, [*lines, f"{name} {data}, v8, s[20:23], 0 idxen offset:4", "s_endpgm"], binding def mubuf_format_store_controls(): @@ -4076,19 +4086,43 @@ def mubuf_format_d16_store_controls(): rejects("Unverified raw UAV store", aot.lower, variant(lines, ("s_waitcnt lgkmcnt(0)", "")), 16, **binding) _, lines, binding = cases[-1] - rejects("Formatted D16 buffer store requires a matching whole-texel format", aot.lower, - variant(lines, ("buffer_store_format_d16_xyzw", "buffer_store_format_d16_xyz")), 16, **binding) rejects("Unverified raw UAV store", aot.lower, variant(lines, ("v[10:11]", "v10")), 16, **binding) + _, lines, binding = next(mubuf_format_store_cases(xyz=True)) + store = lines[-2] + rejects("Formatted D16 XYZ store requires an explicit W-preservation contract", aot.lower, + lines, 16, **(binding | {"mubuf_d16_xyz_mode": None})) + rejects("D16 XYZ mode requires a gfx1030 RGBA16 UINT output binding", aot.lower, + lines, 16, **(binding | {"output_format": "BUF_FMT_16_16_UINT"})) + for replacement, diagnostic in ( + (store.replace("idxen", "offen"), "Unsupported formatted buffer store target or address mode"), + (store.replace("offset:4", "offset:8"), "Unsupported store address"), + (store.replace("v[10:11]", "v[255:256]"), "Unverified raw UAV store"), + (store + " glc", "Unsupported compute instruction"), + (store + "\nbuffer_store_short v10, v8, s[20:23], 0 idxen offset:10", "Overlapping raw UAV stores"), + ): + rejects(diagnostic, aot.lower, variant(lines, (store, replacement)), 16, **binding) + rejects("Unverified raw UAV store", aot.lower, variant(lines, ("s_waitcnt lgkmcnt(0)", "")), 16, **binding) + line = lines[-3] + pending = variant(lines, ("s_waitcnt lgkmcnt(0)", + "s_load_dwordx4 s[16:19], s[12:13], 0x40\ns_waitcnt lgkmcnt(0)"), + (line, "buffer_load_dword v11, v8, s[16:19], 0 idxen")) + read_binding = binding | {"source_descriptor": 0x40, "source_stride": 4} + rejects("Vector load result used or overwritten before s_waitcnt vmcnt(0)", aot.lower, + pending, 16, **read_binding) + aot.lower(variant(pending, (store, "s_waitcnt vmcnt(0)\n" + store)), 16, **read_binding) -def mubuf_format_store_draw(directory, compiler, renderer, backend): + +def mubuf_format_store_draw(directory, compiler, renderer, backend, *, xyz=False): mubuf_format_d16_store_controls() mubuf_format_store_controls() src, cso, case = (directory / f"mubuf-format-store.{ext}" for ext in ("hlsl", "cso", "case")) compile_shader = [compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src] run = [renderer, backend, "--compute-store-case", cso, case] accepted = [] - for name, lines, binding in (*mubuf_format_store_cases(), *mubuf_format_store_cases(packed=True)): + cases = (mubuf_format_store_cases(xyz=True) if xyz else + (*mubuf_format_store_cases(), *mubuf_format_store_cases(packed=True))) + for name, lines, binding in cases: print(f"{name} ({binding['output_format']})", flush=True) components = len(name.rsplit("_", 1)[1]) packed = "_d16_" in name @@ -4115,6 +4149,9 @@ def mubuf_format_store_draw(directory, compiler, renderer, backend): if packed and components == 1: changed = source.replace("& 0xffff0000u", "& 0u") mismatch, actual = 1, MUBUF_STORE_WORDS[0] & 0xffff + elif xyz: + changed = aot.lower(variant(lines, (store, store.replace("_xyz ", "_xyzw "))), 16, **binding) + mismatch, actual = 2, MUBUF_STORE_WORDS[1] elif packed: swapped = "v_lshlrev_b32_e32 v22, 16, v10\nv_lshrrev_b32_e32 v23, 16, v10\nv_or_b32_e32 v10, v22, v23" changed = aot.lower(variant(lines, (store, swapped + "\n" + store)), 16, **binding) @@ -4136,7 +4173,8 @@ def mubuf_format_store_draw(directory, compiler, renderer, backend): raise AssertionError(f"{name}: incorrect store escaped detection\n{bad.stderr}") print(bad.stderr, end="") accepted.append(name) - if record := os.environ.get("FORM_COVERAGE_RECORD"): + # Register the candidate after its native reference has been verified. + if not xyz and (record := os.environ.get("FORM_COVERAGE_RECORD")): path = Path(record) path.parent.mkdir(parents=True, exist_ok=True) path.write_text("\n".join(accepted) + "\n", encoding="utf-8") @@ -5466,6 +5504,7 @@ def draw(directory, compiler, renderer, backend, cases=None): "draw-mubuf-load-format-d16": mubuf_format_d16_draw, "draw-mubuf-format": mubuf_format_draw, "draw-mubuf-format-store": mubuf_format_store_draw, + "draw-mubuf-format-store-xyz": lambda d, *a: mubuf_format_store_draw(d, *a, xyz=True), "draw-mtbuf-load": mtbuf_load_draw, "draw-mimg-load": mimg_load_draw, "draw-mimg-mip": mimg_mip_draw, diff --git a/tests/gfx1030_mubuf_d16/build.sh b/tests/gfx1030_mubuf_d16/build.sh new file mode 100644 index 000000000..3e6e94ce9 --- /dev/null +++ b/tests/gfx1030_mubuf_d16/build.sh @@ -0,0 +1,27 @@ +#!/bin/sh +# SPDX-License-Identifier: MIT +set -eu + +cd "$(dirname "$0")" +llvm_mc=${LLVM_MC_15:-llvm-mc-15} +lld=${LD_LLD_15:-ld.lld-15} +objdump=${LLVM_OBJDUMP_15:-llvm-objdump-15} + +target=${1:-gfx1030} +case "$target" in + gfx1030) source=d16.s; mnemonic=buffer_store_format_d16 ;; + gfx1100) source=d16-gfx1100.s; mnemonic=buffer_store_d16_format ;; + *) echo "Usage: sh build.sh [gfx1030|gfx1100]" >&2; exit 2 ;; +esac + +output="../../out/native-mubuf-d16/$target" +mkdir -p "$output" +"$llvm_mc" -triple=amdgcn-amd-amdhsa -mcpu="$target" -filetype=obj "$source" -o "$output/xyz.o" +"$llvm_mc" -triple=amdgcn-amd-amdhsa -mcpu="$target" -filetype=obj --defsym=CONTROL_XYZW=1 "$source" -o "$output/xyzw.o" +"$lld" -shared "$output/xyz.o" -o "$output/xyz.hsaco" +"$lld" -shared "$output/xyzw.o" -o "$output/xyzw.hsaco" + +for shape in xyz xyzw; do + "$objdump" -d --mcpu="$target" "$output/$shape.hsaco" > "$output/$shape.disasm" + grep -E "${mnemonic}_${shape}[[:space:]]" "$output/$shape.disasm" +done diff --git a/tests/gfx1030_mubuf_d16/check.py b/tests/gfx1030_mubuf_d16/check.py new file mode 100644 index 000000000..a4922c03a --- /dev/null +++ b/tests/gfx1030_mubuf_d16/check.py @@ -0,0 +1,152 @@ +# SPDX-License-Identifier: MIT +"""Run the two synthetic packed D16 store code objects with the Linux HIP runtime.""" +import argparse +import ctypes as ct +import os +from pathlib import Path + + +DESCRIPTOR_RECORDS = 64 +LANES = 32 +GROUPS = (1, 2, 3) +# Allocate even the out-of-bounds dispatch lanes so a failed bounds check is observable. +RECORDS = max(GROUPS) * LANES + 16 +WordArray = ct.c_uint16 * (4 * RECORDS) + + +def initial_words(): + return [0x8100 + i for i in range(4 * RECORDS)] + + +def expected_words(groups, write_w, *, respect_bounds=True): + words = initial_words() + active = groups * LANES + if respect_bounds: + active = min(active, DESCRIPTOR_RECORDS) + for lane in range(active): + packed = (0x1357 ^ lane, 0x2468, 0x389b ^ lane, 0xca5e) + count = 4 if write_w else 3 + words[4 * lane:4 * lane + count] = packed[:count] + return words + + +def first_difference(expected, actual): + for i, (left, right) in enumerate(zip(expected, actual, strict=True)): + if left != right: + return i, left, right + return None + + +def describe(difference): + word, expected, actual = difference + return (f"word={word} record={word // 4} channel={'XYZW'[word % 4]} " + f"expected=0x{expected:04x} actual=0x{actual:04x}") + + +def model_check(): + for groups in GROUPS: + preserve = expected_words(groups, False) + overwrite = expected_words(groups, True) + assert first_difference(preserve, overwrite) == (3, 0x8103, 0xca5e) + tail_start = 4 * min(groups * LANES, DESCRIPTOR_RECORDS) + assert preserve[tail_start:] == initial_words()[tail_start:] + print(f"groups={groups} wrong-W control: {describe(first_difference(preserve, overwrite))}") + for write_w in (False, True): + groups = max(GROUPS) + expected = expected_words(groups, write_w) + unbounded = expected_words(groups, write_w, respect_bounds=False) + difference = first_difference(expected, unbounded) + assert difference == (256, 0x8200, 0x1317) + shape = "xyzw" if write_w else "xyz" + print(f"{shape} groups={groups} missing-bounds control: {describe(difference)}") + + +class Hip: + def __init__(self): + self.library = ct.CDLL("libamdhip64.so") + self.library.hipGetErrorString.argtypes = [ct.c_int] + self.library.hipGetErrorString.restype = ct.c_char_p + integer, unsigned, pointer = ct.c_int, ct.c_uint, ct.c_void_p + signatures = { + "hipInit": [unsigned], "hipSetDevice": [integer], + "hipDeviceGetName": [pointer, integer, integer], + "hipRuntimeGetVersion": [ct.POINTER(integer)], + "hipDriverGetVersion": [ct.POINTER(integer)], + "hipModuleLoad": [ct.POINTER(pointer), ct.c_char_p], + "hipModuleGetFunction": [ct.POINTER(pointer), pointer, ct.c_char_p], + "hipMalloc": [ct.POINTER(pointer), ct.c_size_t], + "hipMemcpy": [pointer, pointer, ct.c_size_t, integer], + "hipModuleLaunchKernel": [pointer] + [unsigned] * 7 + [pointer] * 3, + "hipDeviceSynchronize": [], "hipFree": [pointer], + "hipModuleUnload": [pointer], + } + for name, args in signatures.items(): + fn = getattr(self.library, name) + fn.argtypes = args + fn.restype = integer + + def call(self, name, *args): + status = getattr(self.library, name)(*args) + if status: + detail = self.library.hipGetErrorString(status) + raise RuntimeError(f"{name}: {status} {detail.decode() if detail else ''}") + + def readback(self, path, groups): + module, kernel, output = ct.c_void_p(), ct.c_void_p(), ct.c_void_p() + self.call("hipModuleLoad", ct.byref(module), bytes(path)) + try: + self.call("hipModuleGetFunction", ct.byref(kernel), module, b"store_d16") + self.call("hipMalloc", ct.byref(output), ct.sizeof(WordArray)) + try: + words = WordArray(*initial_words()) + self.call("hipMemcpy", output, words, ct.sizeof(words), 1) # host to device + params = (ct.c_void_p * 1)(ct.cast(ct.byref(output), ct.c_void_p)) + self.call("hipModuleLaunchKernel", kernel, groups, 1, 1, LANES, 1, 1, + 0, None, params, None) + self.call("hipDeviceSynchronize") + self.call("hipMemcpy", words, output, ct.sizeof(words), 2) # device to host + return list(words) + finally: + self.call("hipFree", output) + finally: + self.call("hipModuleUnload", module) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--device", type=int, default=0) + parser.add_argument("--target", choices=("gfx1030", "gfx1100"), default="gfx1030") + parser.add_argument("--model-only", action="store_true") + args = parser.parse_args() + model_check() + if args.model_only: + return + if "HSA_OVERRIDE_GFX_VERSION" in os.environ: + parser.error("Unset HSA_OVERRIDE_GFX_VERSION to measure the actual device target") + directory = Path(__file__).resolve().parents[2] / "out" / "native-mubuf-d16" / args.target + for shape in ("xyz", "xyzw"): + if not (directory / f"{shape}.hsaco").is_file(): + parser.error(f"Build {args.target} first with: sh tests/gfx1030_mubuf_d16/build.sh {args.target}") + hip = Hip() + hip.call("hipInit", 0) + hip.call("hipSetDevice", args.device) + name = ct.create_string_buffer(256) + runtime, driver = ct.c_int(), ct.c_int() + hip.call("hipDeviceGetName", name, len(name), args.device) + hip.call("hipRuntimeGetVersion", ct.byref(runtime)) + hip.call("hipDriverGetVersion", ct.byref(driver)) + print(f"device={name.value.decode()} code_target={args.target} " + f"hip_runtime={runtime.value} hip_driver={driver.value}") + for shape, write_w in (("xyzw", True), ("xyz", False)): + for groups in GROUPS: + path = directory / f"{shape}.hsaco" + actual = hip.readback(path, groups) + expected = expected_words(groups, write_w) + difference = first_difference(expected, actual) + if difference: + raise SystemExit(f"{shape} groups={groups}: {describe(difference)}") + print(f"{shape} groups={groups} compared_halfwords={len(actual)} mismatches=0") + + +if __name__ == "__main__": + main() diff --git a/tests/gfx1030_mubuf_d16/d16-gfx1100.s b/tests/gfx1030_mubuf_d16/d16-gfx1100.s new file mode 100644 index 000000000..9093e2c4e --- /dev/null +++ b/tests/gfx1030_mubuf_d16/d16-gfx1100.s @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT +.amdgcn_target "amdgcn-amd-amdhsa--gfx1100" +.text +.p2align 8 +.globl store_d16 +.type store_d16,@function +store_d16: + // Each workgroup contains one wave32. v0 is the work-item ID within it. + s_lshl_b32 s4, s2, 5 + v_add_nc_u32 v0, s4, v0 + s_load_dwordx2 s[0:1], s[0:1], 0x0 + s_waitcnt lgkmcnt(0) + // Linear stride 8, identity selectors, format 55 (RGBA16 UINT), + // OOB_SELECT 1 with 64 record indices. + s_and_b32 s1, s1, 0xffff + s_or_b32 s1, s1, 0x00080000 + s_mov_b32 s2, 64 + s_mov_b32 s3, 0x10037fac + v_xor_b32 v1, 0x24681357, v0 + v_xor_b32 v2, 0xca5e389b, v0 +.ifdef CONTROL_XYZW + buffer_store_d16_format_xyzw v[1:2], v0, s[0:3], 0 idxen +.else + buffer_store_d16_format_xyz v[1:2], v0, s[0:3], 0 idxen +.endif + s_waitcnt_vscnt null, 0 + s_endpgm +.size store_d16, .-store_d16 + +.rodata +.p2align 6 +.amdhsa_kernel store_d16 + .amdhsa_group_segment_fixed_size 0 + .amdhsa_private_segment_fixed_size 0 + .amdhsa_kernarg_size 8 + .amdhsa_user_sgpr_kernarg_segment_ptr 1 + .amdhsa_system_sgpr_workgroup_id_x 1 + .amdhsa_system_vgpr_workitem_id 0 + .amdhsa_next_free_vgpr 3 + .amdhsa_next_free_sgpr 5 + .amdhsa_wavefront_size32 1 +.end_amdhsa_kernel + +.amdgpu_metadata +--- +amdhsa.version: [1, 0] +amdhsa.kernels: + - .name: store_d16 + .symbol: store_d16.kd + .kernarg_segment_size: 8 + .group_segment_fixed_size: 0 + .private_segment_fixed_size: 0 + .kernarg_segment_align: 8 + .wavefront_size: 32 + .sgpr_count: 5 + .vgpr_count: 3 + .max_flat_workgroup_size: 32 + .reqd_workgroup_size: [32, 1, 1] + .args: + - .name: output + .size: 8 + .offset: 0 + .value_kind: global_buffer + .address_space: global +... +.end_amdgpu_metadata diff --git a/tests/gfx1030_mubuf_d16/d16.s b/tests/gfx1030_mubuf_d16/d16.s new file mode 100644 index 000000000..922c01d0e --- /dev/null +++ b/tests/gfx1030_mubuf_d16/d16.s @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT +.amdgcn_target "amdgcn-amd-amdhsa--gfx1030" +.text +.p2align 8 +.globl store_d16 +.type store_d16,@function +store_d16: + // Each workgroup contains one wave32. v0 is the work-item ID within it. + s_lshl_b32 s4, s2, 5 + v_add_nc_u32 v0, s4, v0 + s_load_dwordx2 s[0:1], s[0:1], 0x0 + s_waitcnt lgkmcnt(0) + // Linear stride 8, identity selectors, format 69 (RGBA16 UINT), + // resource level 1, OOB_SELECT 1 with 64 record indices. + s_and_b32 s1, s1, 0xffff + s_or_b32 s1, s1, 0x00080000 + s_mov_b32 s2, 64 + s_mov_b32 s3, 0x11045fac + v_xor_b32 v1, 0x24681357, v0 + v_xor_b32 v2, 0xca5e389b, v0 +.ifdef CONTROL_XYZW + buffer_store_format_d16_xyzw v[1:2], v0, s[0:3], 0 idxen +.else + buffer_store_format_d16_xyz v[1:2], v0, s[0:3], 0 idxen +.endif + s_waitcnt_vscnt null, 0 + s_endpgm +.size store_d16, .-store_d16 + +.rodata +.p2align 6 +.amdhsa_kernel store_d16 + .amdhsa_group_segment_fixed_size 0 + .amdhsa_private_segment_fixed_size 0 + .amdhsa_kernarg_size 8 + .amdhsa_user_sgpr_kernarg_segment_ptr 1 + .amdhsa_system_sgpr_workgroup_id_x 1 + .amdhsa_system_vgpr_workitem_id 0 + .amdhsa_next_free_vgpr 3 + .amdhsa_next_free_sgpr 5 + .amdhsa_wavefront_size32 1 +.end_amdhsa_kernel + +.amdgpu_metadata +--- +amdhsa.version: [1, 0] +amdhsa.kernels: + - .name: store_d16 + .symbol: store_d16.kd + .kernarg_segment_size: 8 + .group_segment_fixed_size: 0 + .private_segment_fixed_size: 0 + .kernarg_segment_align: 8 + .wavefront_size: 32 + .sgpr_count: 5 + .vgpr_count: 3 + .max_flat_workgroup_size: 32 + .reqd_workgroup_size: [32, 1, 1] + .args: + - .name: output + .size: 8 + .offset: 0 + .value_kind: global_buffer + .address_space: global +... +.end_amdgpu_metadata diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index e28130767..27428518a 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -198,7 +198,8 @@ def labelled(decoded): def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=None, stride=None, constant_descriptor=None, group_reg_y=None, group_reg_z=None, source_descriptor=None, source_stride=None, source_format=None, output_format=None, image_descriptor=None, image_format=None, - image_uav_mip=None, cpu="gfx1013", lds_bytes=0, lds_f32_mode=None, lds_f64_mode=None): + image_uav_mip=None, cpu="gfx1013", lds_bytes=0, lds_f32_mode=None, lds_f64_mode=None, + mubuf_d16_xyz_mode=None): """v0, v1 and v2 are local X, Y and Z; group_reg, group_reg_y and group_reg_z are the group IDs. gfx10 compute waves receive each local ID in its own VGPR. Y and Z are bound only when that @@ -206,6 +207,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N source t0; source_stride is the t0 byte stride that indexed reads use. source_format declares the MUBUF source descriptor format, and output_format declares the u0 descriptor format for formatted MUBUF stores. Both declarations require identity channel selectors. + mubuf_d16_xyz_mode opts into a caller-verified W-preserving RGBA16 store. image_descriptor is the table byte offset of the 8-dword image descriptor. image_format is the caller's statement of the image format inside it. The image binds to t0 for loads or u0 for stores, where image_uav_mip selects the writable subresource and replaces descriptor_offset. @@ -263,6 +265,9 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if output_format is not None and (output_format not in MUBUF_OUTPUT_FORMATS or cpu != "gfx1030" or stride is None): raise ValueError("Unsupported formatted output binding") + if mubuf_d16_xyz_mode is not None and (mubuf_d16_xyz_mode != "preserve-w" + or output_format != MUBUF_D16_OUTPUT_FORMATS[4] or cpu != "gfx1030"): + raise ValueError("D16 XYZ mode requires a gfx1030 RGBA16 UINT output binding") scalar = {table_reg: "table"} for axis, reg in group_regs.items(): scalar[reg] = ("group", axis) @@ -1341,10 +1346,9 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unsupported formatted buffer store target or address mode") if output_format is None: raise ValueError("Formatted buffer stores require an output format") - # Only whole texels with identity selectors are proven here. - if packed and components not in MUBUF_D16_OUTPUT_FORMATS: - raise ValueError("Formatted D16 buffer store requires a matching whole-texel format") - expected = MUBUF_D16_OUTPUT_FORMATS[components] if packed else MUBUF_UINT_FORMATS[components - 1] + if packed and components == 3 and mubuf_d16_xyz_mode != "preserve-w": + raise ValueError("Formatted D16 XYZ store requires an explicit W-preservation contract") + expected = MUBUF_D16_OUTPUT_FORMATS[format_components] if packed else MUBUF_UINT_FORMATS[components - 1] if output_format != expected: raise ValueError("Formatted buffer store width does not match output format") first, *last = map(int, re.findall(r"\d+", m["data"])) @@ -1502,6 +1506,8 @@ def main(): help="Caller-declared MUBUF t0 descriptor format with identity channel selectors") parser.add_argument("--output-format", choices=MUBUF_OUTPUT_FORMATS, help="Caller-declared MUBUF u0 descriptor format with identity channel selectors") + parser.add_argument("--mubuf-d16-xyz-mode", choices=("preserve-w",), + help="Experimental RGBA16 UINT store with caller-verified preservation of W") parser.add_argument("--image-descriptor", type=lambda n: int(n, 0), help="Table byte offset of the 8-dword image descriptor bound to t0 or u0") parser.add_argument("--image-uav-mip", type=int, @@ -1527,7 +1533,8 @@ def main(): output_format=args.output_format, image_descriptor=args.image_descriptor, image_format=args.image_format, image_uav_mip=args.image_uav_mip, cpu=args.cpu, lds_bytes=args.lds_bytes, - lds_f32_mode=args.lds_f32_mode, lds_f64_mode=args.lds_f64_mode) + lds_f32_mode=args.lds_f32_mode, lds_f64_mode=args.lds_f64_mode, + mubuf_d16_xyz_mode=args.mubuf_d16_xyz_mode) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(source, encoding="ascii") print(json.dumps({"container_sha256": hashlib.sha256(blob).hexdigest(), From c19508ddb9f2d35881b7bcdb324192e159468123 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:49:35 +0100 Subject: [PATCH 061/775] startup_stubs: filter GameInput history by device, keep extended scan codes, skip modifier aliases, separate handle lookups --- src/startup_stubs/gameinput.cpp | 92 +++++++++++++++++++++++-------- tests/startup_gameinput_keys.cpp | 95 +++++++++++++++++++++++++++++++- 2 files changed, 162 insertions(+), 25 deletions(-) diff --git a/src/startup_stubs/gameinput.cpp b/src/startup_stubs/gameinput.cpp index e19def8f3..0e5663b51 100644 --- a/src/startup_stubs/gameinput.cpp +++ b/src/startup_stubs/gameinput.cpp @@ -186,12 +186,14 @@ std::uint32_t sample_keys(KeyState* out, std::size_t capacity) { std::uint32_t count = 0; auto push_vk = [&](std::uint32_t vk) { - if (count >= capacity || vk == 0 || vk > 0xFE) return; + // VK_SHIFT/VK_CONTROL/VK_MENU are aliases of the left/right keys, never a physical key of their own. + if (count >= capacity || vk == 0 || vk > 0xFE || vk == VK_SHIFT || vk == VK_CONTROL || vk == VK_MENU) return; const auto vkey = static_cast(vk); for (std::uint32_t i = 0; i < count; ++i) if (out[i].virtualKey == vkey) return; KeyState ks{}; - ks.scanCode = static_cast(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC)); + // _EX keeps the 0xE0/0xE1 prefix, so Left Arrow (0xE04B) differs from keypad 4 (0x4B). + ks.scanCode = static_cast(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC_EX)); const UINT ch = MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR); if ((ch & 0x80000000u) == 0 && (ch & 0xFFFFu) != 0) ks.codePoint = ch & 0xFFFFu; ks.virtualKey = vkey; @@ -273,11 +275,13 @@ struct Reading : Object { KeyState keys[max_keys]; u64 sequence, timestamp; }; +constexpr std::uint32_t history_pad = 1, history_keys = 2; struct HistoryEntry { u64 sequence, timestamp; GamepadState pad; std::uint32_t key_count; KeyState keys[max_keys]; + std::uint32_t changed; // history_pad / history_keys: which device's state differs from the previous entry }; Table<32> reading_table; volatile LONG64 sequence_counter; @@ -360,13 +364,13 @@ HistoryEntry capture_current() const std::uint32_t key_count = sample_keys(keys, max_keys); AcquireSRWLockExclusive(&state_lock); - bool changed = (history_count == 0); + std::uint32_t changed = (history_count == 0) ? (history_pad | history_keys) : 0; if (!changed) { const HistoryEntry& latest = history_ring[static_cast(sequence_counter) % history_capacity]; - if (std::memcmp(&pad, &latest.pad, sizeof(pad)) != 0 || key_count != latest.key_count || - (key_count > 0 && std::memcmp(keys, latest.keys, key_count * sizeof(KeyState)) != 0)) { - changed = true; - } + if (std::memcmp(&pad, &latest.pad, sizeof(pad)) != 0) changed |= history_pad; + if (key_count != latest.key_count || + (key_count > 0 && std::memcmp(keys, latest.keys, key_count * sizeof(KeyState)) != 0)) + changed |= history_keys; } if (changed) { ++sequence_counter; @@ -374,6 +378,7 @@ HistoryEntry capture_current() slot.sequence = static_cast(sequence_counter); slot.timestamp = now_microseconds(); slot.pad = pad; + slot.changed = changed; slot.key_count = key_count; if (key_count > 0) std::memcpy(slot.keys, keys, key_count * sizeof(KeyState)); if (history_count < history_capacity) ++history_count; @@ -383,22 +388,39 @@ HistoryEntry capture_current() return result; } -// Returns 0 on hit, -1 if sequence does not exist (not found), -2 if evicted (too old). -int find_history(u64 seq, HistoryEntry& out) +std::uint32_t history_mask(std::uint32_t reading_kind) +{ + return ((reading_kind & kind_gamepad) ? history_pad : 0) | ((reading_kind & kind_keyboard) ? history_keys : 0); +} + +// Walks the history from `start` in `step` (+1 / -1) to the nearest entry that changed the wanted device(s). +// Returns 0 on hit, -1 if there is none (not found), -2 if the walk ran past the evicted end (too old). +int find_history(u64 start, int step, std::uint32_t mask, HistoryEntry& out) { AcquireSRWLockShared(&state_lock); - if (history_count == 0 || seq == 0 || seq > static_cast(sequence_counter)) { - ReleaseSRWLockShared(&state_lock); - return -1; - } - const u64 oldest = static_cast(sequence_counter) - history_count + 1; - if (seq < oldest) { - ReleaseSRWLockShared(&state_lock); - return -2; + int result = -1; + const u64 latest = static_cast(sequence_counter); + if (history_count != 0 && start != 0 && start <= latest) { + const u64 oldest = latest - history_count + 1; + if (start < oldest) { + result = -2; + } else { + for (u64 seq = start; seq >= oldest && seq <= latest; seq += static_cast(static_cast(step))) { + const HistoryEntry& entry = history_ring[seq % history_capacity]; + if (entry.changed & mask) { + out = entry; + result = 0; + break; + } + if (step < 0 && seq == oldest) { + result = oldest > 1 ? -2 : -1; + break; + } + } + } } - out = history_ring[seq % history_capacity]; ReleaseSRWLockShared(&state_lock); - return 0; + return result; } Reading* make_reading(const HistoryEntry& entry, std::uint32_t kind, Object* device) @@ -453,7 +475,7 @@ HRESULT __stdcall input_next_reading(Object*, Reading* reference, std::uint32_t if (FAILED(check_hr)) return check_hr; capture_current(); HistoryEntry entry{}; - const int found = find_history(reference->sequence + 1, entry); + const int found = find_history(reference->sequence + 1, 1, history_mask(resolve_reading_kind(kind, device)), entry); if (found == -2) return reading_too_old; if (found != 0) return reading_not_found; *out = make_reading(entry, kind, device); @@ -470,7 +492,7 @@ HRESULT __stdcall input_previous_reading(Object*, Reading* reference, std::uint3 if (FAILED(check_hr)) return check_hr; if (reference->sequence <= 1) return reading_not_found; HistoryEntry entry{}; - const int found = find_history(reference->sequence - 1, entry); + const int found = find_history(reference->sequence - 1, -1, history_mask(resolve_reading_kind(kind, device)), entry); if (found == -2) return reading_too_old; if (found != 0) return reading_not_found; *out = make_reading(entry, kind, device); @@ -513,10 +535,10 @@ HRESULT __stdcall input_register_short_callback(Object*, Object*, void*, void*, } void __stdcall input_stop_callback(Object*, u64) {} bool __stdcall input_unregister_callback(Object*, u64, u64) { return true; } -HRESULT __stdcall input_find_device(Object*, const void* id, Object** device) +HRESULT __stdcall input_find_device_by_id(Object*, const void* id, Object** device) { static LONG calls; - note("GameInput::FindDeviceFrom*", calls); + note("GameInput::FindDeviceFromId", calls); if (!device) return E_POINTER; if (id && (std::memcmp(id, keyboard_device_info + 0x20, 32) == 0 || std::memcmp(id, keyboard_device_info + 0x40, 32) == 0)) { @@ -528,6 +550,25 @@ HRESULT __stdcall input_find_device(Object*, const void* id, Object** device) *device = &the_device; return S_OK; } +// FindDeviceFromPlatformHandle: the argument is an opaque OS handle, never a pointer; no device is bound to one. +HRESULT __stdcall input_find_device_by_handle(Object*, void*, Object** device) +{ + static LONG calls; + note("GameInput::FindDeviceFromPlatformHandle", calls); + if (!device) return E_POINTER; + *device = nullptr; + return device_not_found; +} +// FindDeviceFromObject / FindDeviceFromPlatformString: the argument is not read; the virtual pad answers. +HRESULT __stdcall input_find_device_other(Object*, const void*, Object** device) +{ + static LONG calls; + note("GameInput::FindDeviceFrom{Object,PlatformString}", calls); + if (!device) return E_POINTER; + InterlockedIncrement(&the_device.refs); + *device = &the_device; + return S_OK; +} void __stdcall input_set_focus_policy(Object*, std::uint32_t policy) { static LONG calls; @@ -558,7 +599,10 @@ void build() input_table.slots[11] = reinterpret_cast(&input_register_short_callback); // RegisterKeyboardLayoutCallback input_table.slots[12] = reinterpret_cast(&input_stop_callback); input_table.slots[13] = reinterpret_cast(&input_unregister_callback); - for (int slot = 16; slot <= 19; ++slot) input_table.slots[slot] = reinterpret_cast(&input_find_device); + input_table.slots[16] = reinterpret_cast(&input_find_device_by_id); + input_table.slots[17] = reinterpret_cast(&input_find_device_other); + input_table.slots[18] = reinterpret_cast(&input_find_device_by_handle); + input_table.slots[19] = reinterpret_cast(&input_find_device_other); input_table.slots[21] = reinterpret_cast(&input_set_focus_policy); // IGameInputDevice. device_table.slots[3] = reinterpret_cast(&device_get_info); diff --git a/tests/startup_gameinput_keys.cpp b/tests/startup_gameinput_keys.cpp index ac06ac4b9..6b9cfdfbf 100644 --- a/tests/startup_gameinput_keys.cpp +++ b/tests/startup_gameinput_keys.cpp @@ -128,6 +128,11 @@ struct IGameInput { return reinterpret_cast(vtbl[9])(this, device, kind, statusFilter, enumerationKind, context, callback, token); } + HRESULT FindDevice(int slot, const void* arg, IGameInputDevice** device) + { + using Fn = HRESULT(__stdcall*)(IGameInput*, const void*, IGameInputDevice**); + return reinterpret_cast(vtbl[slot])(this, arg, device); + } bool UnregisterCallback(std::uint64_t token, std::uint64_t timeoutUs) { using Fn = bool(__stdcall*)(IGameInput*, std::uint64_t, std::uint64_t); @@ -292,6 +297,91 @@ int main(int argc, char** argv) combo->Release(); } + // 5b. Extended scan-code prefixes survive; generic modifier aliases are not reported as keys. + SetEnvironmentVariableA("X2W_INPUT_KEYS", "25,64,A3,A5"); // Left, Numpad4, RCtrl, RAlt + IGameInputReading* ext = nullptr; + hr = input->GetCurrentReading(kind_keyboard, kbd_device, &ext); + failures += check(hr == S_OK && ext != nullptr, "extended-key reading should succeed"); + if (ext) { + KeyState ek[8]{}; + failures += check(ext->GetKeyState(8, ek) == 4, "extended-key reading should report 4 keys"); + failures += check(ek[0].scanCode == 0xE04B, "Left Arrow scan code should keep the E0 prefix"); + failures += check(ek[1].scanCode == 0x4B, "Numpad 4 scan code should have no prefix"); + failures += check(ek[2].scanCode == 0xE01D, "Right Ctrl scan code should keep the E0 prefix"); + failures += check(ek[3].scanCode == 0xE038, "Right Alt scan code should keep the E0 prefix"); + ext->Release(); + } + SetEnvironmentVariableA("X2W_INPUT_KEYS", "10,11,12,A0,A2"); // generic Shift/Ctrl/Alt, then LShift, LCtrl + hr = input->GetCurrentReading(kind_keyboard, kbd_device, &ext); + failures += check(hr == S_OK && ext != nullptr, "modifier reading should succeed"); + if (ext) { + KeyState mk[8]{}; + const std::uint32_t n = ext->GetKeyState(8, mk); + failures += check(n == 2 && ext->GetKeyCount() == 2, "generic modifier aliases should be skipped"); + failures += check(n == 2 && mk[0].virtualKey == 0xA0 && mk[1].virtualKey == 0xA2, "left modifiers should remain"); + ext->Release(); + } + + // 5c. History traversal is filtered by device: keyboard-only changes are invisible to a gamepad caller. + SetEnvironmentVariableA("X2W_INPUT_KEYS", nullptr); + HANDLE pad_map = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 16, L"Local\\x2w_input_pad"); + auto* pad_words = pad_map ? static_cast(MapViewOfFile(pad_map, FILE_MAP_ALL_ACCESS, 0, 0, 16)) : nullptr; + failures += check(pad_words != nullptr, "shared pad block should be mappable"); + if (pad_words) { + pad_words[1] = 2; // buttons: View + IGameInputReading *pad_a = nullptr, *pad_b = nullptr, *pad_c = nullptr, *tmp = nullptr; + failures += check(input->GetCurrentReading(kind_gamepad, pad_device, &pad_a) == S_OK && pad_a, "pad_a reading"); + const std::uint64_t base = pad_a ? pad_a->GetSequenceNumber(kind_gamepad) : 0; + SetEnvironmentVariableA("X2W_INPUT_KEYS", "51"); + input->GetCurrentReading(kind_keyboard, kbd_device, &tmp); + if (tmp) tmp->Release(); + SetEnvironmentVariableA("X2W_INPUT_KEYS", "52"); + input->GetCurrentReading(kind_keyboard, kbd_device, &tmp); + if (tmp) tmp->Release(); + tmp = nullptr; + failures += check(input->GetNextReading(pad_a, kind_gamepad, pad_device, &tmp) == reading_not_found && tmp == nullptr, + "keyboard-only changes must not be a next gamepad reading"); + pad_words[1] = 4; // buttons: A + input->GetCurrentReading(kind_keyboard, kbd_device, &pad_c); // records the pad change + failures += check(input->GetNextReading(pad_a, kind_gamepad, pad_device, &pad_b) == S_OK && pad_b, "next gamepad reading"); + if (pad_b) { + GamepadState gs{}; + failures += check(pad_b->GetGamepadState(&gs) && gs.buttons == 4, "next gamepad reading carries the new buttons"); + failures += check(pad_b->GetSequenceNumber(kind_gamepad) == base + 3, "next gamepad reading skips keyboard-only entries"); + IGameInputReading* back = nullptr; + failures += check(input->GetPreviousReading(pad_b, kind_gamepad, pad_device, &back) == S_OK && back, "previous gamepad reading"); + if (back) { + failures += check(back->GetSequenceNumber(kind_gamepad) == base, "previous gamepad reading skips keyboard-only entries"); + back->Release(); + } + IGameInputReading* kback = nullptr; + failures += check(input->GetPreviousReading(pad_b, kind_keyboard, kbd_device, &kback) == S_OK && kback, "previous keyboard reading"); + if (kback) { + failures += check(kback->GetSequenceNumber(kind_keyboard) == base + 2, "previous keyboard reading skips pad-only entries"); + kback->Release(); + } + pad_b->Release(); + } + if (pad_a) pad_a->Release(); + if (pad_c) pad_c->Release(); + pad_words[1] = 0; + UnmapViewOfFile(const_cast(pad_words)); + } + if (pad_map) CloseHandle(pad_map); + SetEnvironmentVariableA("X2W_INPUT_KEYS", "42"); + + // 5d. Device lookups: by id, and an opaque platform handle that must never be dereferenced. + using GetInfoFn = const unsigned char*(__stdcall*)(IGameInputDevice*); + if (kbd_device) { + const unsigned char* kinfo = reinterpret_cast(kbd_device->vtbl[3])(kbd_device); + IGameInputDevice* found = nullptr; + failures += check(input->FindDevice(16, kinfo + 0x20, &found) == S_OK && found == kbd_device, "FindDeviceFromId(keyboard id)"); + found = nullptr; + failures += check(input->FindDevice(18, reinterpret_cast(static_cast(4)), &found) == device_not_found && + found == nullptr, + "FindDeviceFromPlatformHandle(0x4) should fail without dereferencing the handle"); + } + // 6. Negative controls: null out, wrong kind, mismatched device, null reference for GetPreviousReading. IGameInputReading* bad = nullptr; failures += check(input->GetCurrentReading(kind_keyboard, nullptr, nullptr) == E_POINTER, @@ -313,9 +403,12 @@ int main(int argc, char** argv) failures += check((hr == device_not_found || hr == reading_not_found) && bad == nullptr, "GetCurrentReading(fake_device) should fail"); // No next reading past latest. - failures += check(input->GetNextReading(r2, kind_keyboard, kbd_device, &bad) == reading_not_found && + IGameInputReading* latest = nullptr; + failures += check(input->GetCurrentReading(kind_keyboard, kbd_device, &latest) == S_OK && latest, "latest reading"); + failures += check(input->GetNextReading(latest, kind_keyboard, kbd_device, &bad) == reading_not_found && bad == nullptr, "GetNextReading(latest) should return reading_not_found"); + if (latest) latest->Release(); } if (r0) r0->Release(); From fb2a4c08486325b4404b3a6398c7d8e344edc6df Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:49:37 +0100 Subject: [PATCH 062/775] startup_stubs/audio_sink: add multi-channel downmix and linear resampling --- docs/startup-runtime.md | 5 +- src/startup_stubs/audio_sink.cpp | 16 ++--- src/startup_stubs/audio_sink.h | 118 ++++++++++++++++++++++++++++--- tests/startup_audio_output.cpp | 18 +++++ tests/startup_audio_pure_check.h | 92 +++++++++++++++++++++++- 5 files changed, 229 insertions(+), 20 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9ff8d97c1..7a4f8e48b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -461,7 +461,10 @@ These are measured on one executable; treat them as hypotheses for others. `src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only), converts each submitted block (format, frame count, bytes) to it, and writes it through -`IAudioRenderClient`. Consumed frames are the submitted frames minus `GetCurrentPadding`; the +`IAudioRenderClient`. `convert_block` supports mono, stereo, 5.1, and 7.1 inputs (using ITU-R BS.775-1 +fold-down coefficients with clamping when downmixing to stereo or mono) and linear sample-rate +resampling when the submitted rate differs from the endpoint mix rate (rejecting invalid rates, +unsupported channel counts, or empty blocks as `Submit::Unsupported`). Consumed frames are the submitted frames minus `GetCurrentPadding`; the `IAudioClock` position is reported next to them. It records the first accepted block, the submitted format, per-block frame counts and peak amplitude, the drained interval (queue empty while the producer withholds data) and the recovery (resume until consumption advances). The diff --git a/src/startup_stubs/audio_sink.cpp b/src/startup_stubs/audio_sink.cpp index e2aaa653f..bdc6d101c 100644 --- a/src/startup_stubs/audio_sink.cpp +++ b/src/startup_stubs/audio_sink.cpp @@ -124,30 +124,30 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt { const uint32_t call = calls_++; if (!p_) return Submit::NotOpen; - std::vector conv; - if (!convert_block(in, bytes, frames, mix_, conv)) { + if (!convert_block(in, bytes, frames, mix_, conv_buf_)) { ++r_.unsupported; return Submit::Unsupported; } + const uint32_t out_frames = static_cast(conv_buf_.size() / mix_.frame_bytes()); const uint32_t pad = padding(); if (pad == padding_failed) return Submit::NotOpen; - if (frames > buffer_frames_ - pad) { + if (out_frames > buffer_frames_ - pad) { ++r_.rejected_full; return Submit::Full; } observe(false); if (timer_.drained_start >= 0) timer_.resume(now_ms(), r_.consumed_frames); // the producer is back BYTE* dst = nullptr; - if (FAILED(p_->render->GetBuffer(frames, &dst)) || !dst) return Submit::NotOpen; - std::memcpy(dst, conv.data(), conv.size()); - if (FAILED(p_->render->ReleaseBuffer(frames, 0))) return Submit::NotOpen; + if (FAILED(p_->render->GetBuffer(out_frames, &dst)) || !dst) return Submit::NotOpen; + std::memcpy(dst, conv_buf_.data(), conv_buf_.size()); + if (FAILED(p_->render->ReleaseBuffer(out_frames, 0))) return Submit::NotOpen; if (r_.first_block < 0) { r_.first_block = call; r_.submitted = in; } - r_.frames.push_back(frames); + r_.frames.push_back(out_frames); r_.peaks.push_back(block_peak(in, bytes, frames)); - r_.submitted_frames += frames; + r_.submitted_frames += out_frames; if (!started_ && SUCCEEDED(p_->client->Start())) started_ = true; return Submit::Accepted; } diff --git a/src/startup_stubs/audio_sink.h b/src/startup_stubs/audio_sink.h index cc04def09..ff00efde7 100644 --- a/src/startup_stubs/audio_sink.h +++ b/src/startup_stubs/audio_sink.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -47,22 +48,120 @@ inline void write_sample(const BlockFormat& f, void* dst, size_t i, float s) // Largest absolute sample in 0..1. Exactly 0 means every sample is zero: a valid silent block. inline float block_peak(const BlockFormat& f, const void* data, uint32_t frames) { + if (!data || frames == 0 || f.channels == 0) return 0.0f; float peak = 0.0f; - for (size_t i = 0; i < size_t(frames) * f.channels; ++i) peak = std::max(peak, std::fabs(read_sample(f, data, i))); + for (size_t i = 0; i < size_t(frames) * f.channels; ++i) + peak = (std::max)(peak, std::fabs(read_sample(f, data, i))); return peak; } -// Converts a submitted block to the endpoint format. Same rate required; mono is copied to every -// channel, otherwise channel counts must match. Returns false for any other combination. +inline bool is_valid_sample_rate(uint32_t rate) +{ + return rate >= 1000u && rate <= 384000u; +} + +inline bool is_supported_channel_count(uint32_t channels) +{ + return channels == 1u || channels == 2u || channels == 6u || channels == 8u; +} + +inline bool is_supported_channel_conversion(uint32_t in_ch, uint32_t out_ch) +{ + if (!is_supported_channel_count(in_ch) || !is_supported_channel_count(out_ch)) return false; + if (in_ch == out_ch || in_ch == 1u) return true; + if (in_ch == 2u && out_ch == 1u) return true; + if ((in_ch == 6u || in_ch == 8u) && (out_ch == 1u || out_ch == 2u)) return true; + return false; +} + +// ITU-R BS.775-1 fold-down coefficient (1 / sqrt(2)) for center and surround channels. +inline constexpr float kItuSurroundCoeff = 0.7071067811865475f; + +inline float read_channel_mapped_sample(const BlockFormat& in, const void* src, size_t frame, uint32_t out_ch, + uint32_t out_channels) +{ + const size_t base = frame * in.channels; + if (in.channels == out_channels) return read_sample(in, src, base + out_ch); + if (in.channels == 1u) return read_sample(in, src, base); + if (in.channels == 2u && out_channels == 1u) { + const float left = read_sample(in, src, base); + const float right = read_sample(in, src, base + 1); + return std::clamp(0.5f * (left + right), -1.0f, 1.0f); + } + // 5.1 (FL, FR, FC, LFE, BL, BR) or 7.1 (FL, FR, FC, LFE, BL, BR, SL, SR) -> stereo / mono. + const float fl = read_sample(in, src, base + 0); + const float fr = read_sample(in, src, base + 1); + const float fc = read_sample(in, src, base + 2); + const float bl = read_sample(in, src, base + 4); + const float br = read_sample(in, src, base + 5); + float left = fl + kItuSurroundCoeff * fc + kItuSurroundCoeff * bl; + float right = fr + kItuSurroundCoeff * fc + kItuSurroundCoeff * br; + if (in.channels == 8u) { + const float sl = read_sample(in, src, base + 6); + const float sr = read_sample(in, src, base + 7); + left += kItuSurroundCoeff * sl; + right += kItuSurroundCoeff * sr; + } + left = std::clamp(left, -1.0f, 1.0f); + right = std::clamp(right, -1.0f, 1.0f); + if (out_channels == 1u) return std::clamp(0.5f * (left + right), -1.0f, 1.0f); + return out_ch == 0u ? left : right; +} + +inline uint32_t resampled_frame_count(uint32_t frames, uint32_t in_rate, uint32_t out_rate) +{ + if (frames == 0 || !is_valid_sample_rate(in_rate) || !is_valid_sample_rate(out_rate)) return 0; + if (in_rate == out_rate) return frames; + const uint64_t num = static_cast(frames) * out_rate + (in_rate / 2u); + const uint64_t scaled = (std::max)(uint64_t{1}, num / in_rate); + if (scaled > (std::numeric_limits::max)()) return 0; + return static_cast(scaled); +} + +// Converts a submitted block to the endpoint format, supporting mono/stereo/5.1/7.1 channel mapping +// (ITU-R BS.775-1 fold-down with clamping) and linear sample-rate resampling. +// Preserves exact bit-for-bit behavior for matching-rate 1:1 and mono-to-N paths. inline bool convert_block(const BlockFormat& in, const void* src, uint32_t frames, const BlockFormat& out, std::vector& dst) { - if (in.rate != out.rate || in.channels == 0 || out.channels == 0) return false; - if (in.channels != out.channels && in.channels != 1) return false; - dst.assign(size_t(frames) * out.frame_bytes(), 0); - for (size_t f = 0; f < frames; ++f) - for (size_t c = 0; c < out.channels; ++c) - write_sample(out, dst.data(), f * out.channels + c, read_sample(in, src, f * in.channels + (in.channels == 1 ? 0 : c))); + if (!src || frames == 0) return false; + if (!is_valid_sample_rate(in.rate) || !is_valid_sample_rate(out.rate)) return false; + if (!is_supported_channel_conversion(in.channels, out.channels)) return false; + + const uint32_t out_frames = resampled_frame_count(frames, in.rate, out.rate); + if (out_frames == 0) return false; + const uint64_t total_bytes = static_cast(out_frames) * out.frame_bytes(); + if (total_bytes > (std::numeric_limits::max)()) return false; + dst.resize(static_cast(total_bytes)); + + if (in.rate == out.rate) { + if (in.channels == out.channels || in.channels == 1u) { + for (size_t f = 0; f < frames; ++f) + for (size_t c = 0; c < out.channels; ++c) + write_sample(out, dst.data(), f * out.channels + c, + read_sample(in, src, f * in.channels + (in.channels == 1u ? 0 : c))); + return true; + } + for (size_t f = 0; f < frames; ++f) + for (uint32_t c = 0; c < out.channels; ++c) + write_sample(out, dst.data(), f * out.channels + c, + read_channel_mapped_sample(in, src, f, c, out.channels)); + return true; + } + + const double step = static_cast(in.rate) / static_cast(out.rate); + for (uint32_t f = 0; f < out_frames; ++f) { + const double pos = static_cast(f) * step; + const uint32_t i0 = (std::min)(static_cast(pos), frames - 1u); + const uint32_t i1 = (std::min)(i0 + 1u, frames - 1u); + const float frac = static_cast(pos - static_cast(i0)); + for (uint32_t c = 0; c < out.channels; ++c) { + const float s0 = read_channel_mapped_sample(in, src, i0, c, out.channels); + const float s1 = (i1 == i0) ? s0 : read_channel_mapped_sample(in, src, i1, c, out.channels); + const float interp = std::clamp(s0 + frac * (s1 - s0), -1.0f, 1.0f); + write_sample(out, dst.data(), static_cast(f) * out.channels + c, interp); + } + } return true; } @@ -144,6 +243,7 @@ class AudioSink { bool started_ = false; Report r_; StarvationTimer timer_; + std::vector conv_buf_; }; #endif diff --git a/tests/startup_audio_output.cpp b/tests/startup_audio_output.cpp index adea3ca7f..15763a3ce 100644 --- a/tests/startup_audio_output.cpp +++ b/tests/startup_audio_output.cpp @@ -133,6 +133,24 @@ int run() if (rc.consumed_frames != 3ull * block) return fail("case c consumption incomplete", 10); // A failed padding query is not a measurement: reject the run instead of counting frames as consumed. if (ra.padding_errors || rb.padding_errors || rc.padding_errors) return fail("GetCurrentPadding failed during a case (endpoint lost?)", 11); + + // (d) Negative control + 5.1 / 44.1 kHz downmix & resample submission when endpoint is mono or stereo. + if (mix.channels <= 2) { + AudioSink d; + if (const std::string why = d.open(); !why.empty()) return skip(why); + const BlockFormat invalid_fmt{SampleKind::Float32, 2, 0}; + const float zero_pair[2] = {0.0f, 0.0f}; + if (d.submit(invalid_fmt, 1, zero_pair) != Submit::Unsupported) + return fail("case d zero sample rate was not rejected as Unsupported", 12); + const BlockFormat ch6_44{SampleKind::Float32, 6, 44100}; + std::vector blk6(441 * 6, 0.0f); + for (uint32_t i = 0; i < 441; ++i) blk6[i * 6 + 0] = 0.1f; + if (d.submit(ch6_44, 441, blk6.data()) != Submit::Accepted) + return fail("case d 5.1 44.1 kHz block not accepted", 13); + const Report rd = d.report(); + if (rd.unsupported != 1 || rd.submitted_frames != resampled_frame_count(441, 44100, mix.rate)) + return fail("case d report counts mismatch", 14); + } std::puts("startup_audio_output: PASS (no capture-path verification; glitch count not available from the render API)"); return 0; } diff --git a/tests/startup_audio_pure_check.h b/tests/startup_audio_pure_check.h index d8512d41d..3c650936a 100644 --- a/tests/startup_audio_pure_check.h +++ b/tests/startup_audio_pure_check.h @@ -33,8 +33,96 @@ inline int check_pure() const BlockFormat mono_f{SampleKind::Float32, 1, 48000}; if (!convert_block(mono16, tone.data(), 480, mono_f, out) || !convert_block(mono_f, out.data(), 480, mono16, back) || std::memcmp(back.data(), tone.data(), 960) != 0) return 15; - if (convert_block(mono16, tone.data(), 480, {SampleKind::Pcm16, 1, 44100}, out)) return 16; // rate mismatch - if (convert_block(stereo16, out.data(), 120, {SampleKind::Pcm16, 6, 48000}, back)) return 17; // channel mismatch + if (!convert_block(mono16, tone.data(), 480, {SampleKind::Pcm16, 1, 44100}, out) || out.size() != 441 * 2) return 16; + if (convert_block(stereo16, out.data(), 120, {SampleKind::Pcm16, 6, 48000}, back)) return 17; // unsupported upmix + + // Stereo -> mono fold-down. + { + const float st_data[4] = {0.8f, -0.2f, 0.4f, 0.4f}; + const BlockFormat st_f{SampleKind::Float32, 2, 48000}; + if (!convert_block(st_f, st_data, 2, mono_f, out) || out.size() != 8) return 30; + if (std::fabs(read_sample(mono_f, out.data(), 0) - 0.3f) > 1e-6f) return 31; + if (std::fabs(read_sample(mono_f, out.data(), 1) - 0.4f) > 1e-6f) return 32; + } + + // 5.1 (6ch) -> stereo ITU-R BS.775-1 downmix accuracy, LFE omission, and clamping. + { + const BlockFormat ch6_f{SampleKind::Float32, 6, 48000}; + // Frame 0: FL=0.5, FR=0.25, FC=0.4, LFE=0.9 (ignored), BL=0.2, BR=-0.2 + // Frame 1: FL=1.0, FR=-1.0, FC=1.0, LFE=0.0, BL=1.0, BR=-1.0 -> clamped to [+1.0, -1.0] + const float src6[12] = { + 0.5f, 0.25f, 0.4f, 0.9f, 0.2f, -0.2f, + 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, + }; + if (!convert_block(ch6_f, src6, 2, stereo_f, out) || out.size() != 16) return 33; + const float exp_l0 = 0.5f + kItuSurroundCoeff * 0.4f + kItuSurroundCoeff * 0.2f; + const float exp_r0 = 0.25f + kItuSurroundCoeff * 0.4f + kItuSurroundCoeff * (-0.2f); + if (std::fabs(read_sample(stereo_f, out.data(), 0) - exp_l0) > 1e-5f) return 34; + if (std::fabs(read_sample(stereo_f, out.data(), 1) - exp_r0) > 1e-5f) return 35; + if (read_sample(stereo_f, out.data(), 2) != 1.0f) return 36; + if (read_sample(stereo_f, out.data(), 3) != -1.0f) return 37; + } + + // 7.1 (8ch) -> stereo ITU/SMPTE downmix accuracy & side/back weighting. + { + const BlockFormat ch8_f{SampleKind::Float32, 8, 48000}; + // FL=0.2, FR=0.1, FC=0.3, LFE=0.8, BL=0.1, BR=0.2, SL=0.4, SR=-0.1 + const float src8[8] = {0.2f, 0.1f, 0.3f, 0.8f, 0.1f, 0.2f, 0.4f, -0.1f}; + if (!convert_block(ch8_f, src8, 1, stereo_f, out) || out.size() != 8) return 38; + const float exp_l = 0.2f + kItuSurroundCoeff * 0.3f + kItuSurroundCoeff * (0.1f + 0.4f); + const float exp_r = 0.1f + kItuSurroundCoeff * 0.3f + kItuSurroundCoeff * (0.2f - 0.1f); + if (std::fabs(read_sample(stereo_f, out.data(), 0) - exp_l) > 1e-5f) return 39; + if (std::fabs(read_sample(stereo_f, out.data(), 1) - exp_r) > 1e-5f) return 40; + } + + // 24 kHz -> 48 kHz and 44.1 kHz -> 48 kHz linear resampling frame counts & signal preservation. + { + const BlockFormat mono24{SampleKind::Pcm16, 1, 24000}; + const auto tone24 = make_tone(24000, 240, 440.0, 0.5); + if (!convert_block(mono24, tone24.data(), 240, mono_f, out) || out.size() != 480 * 4) return 41; + if (block_peak(mono_f, out.data(), 480) < 0.45f) return 42; + + // Constant DC preservation across 44.1 kHz -> 48 kHz. + const BlockFormat mono44_f{SampleKind::Float32, 1, 44100}; + const std::vector dc44(441, 0.625f); + if (!convert_block(mono44_f, dc44.data(), 441, mono_f, out) || out.size() != 480 * 4) return 43; + for (uint32_t i = 0; i < 480; ++i) + if (std::fabs(read_sample(mono_f, out.data(), i) - 0.625f) > 1e-6f) return 44; + + // 44.1 kHz -> 48 kHz sine tone peak preservation (40 ms: 1764 -> 1920 frames). + const BlockFormat mono44{SampleKind::Pcm16, 1, 44100}; + const auto tone44 = make_tone(44100, 1764, 440.0, 0.5); + if (!convert_block(mono44, tone44.data(), 1764, mono_f, out) || out.size() != 1920 * 4) return 45; + const float pk = block_peak(mono_f, out.data(), 1920); + if (pk < 0.48f || pk > 0.51f) return 46; + } + + // Combined 5.1 44.1 kHz -> stereo 48 kHz conversion. + { + const BlockFormat ch6_44{SampleKind::Float32, 6, 44100}; + std::vector src6_44(441 * 6, 0.0f); + for (uint32_t i = 0; i < 441; ++i) { + src6_44[i * 6 + 0] = 0.25f; + src6_44[i * 6 + 2] = 0.25f; + } + if (!convert_block(ch6_44, src6_44.data(), 441, stereo_f, out) || out.size() != 480 * 8) return 47; + const float exp_l = 0.25f + kItuSurroundCoeff * 0.25f; + const float exp_r = kItuSurroundCoeff * 0.25f; + if (std::fabs(read_sample(stereo_f, out.data(), 0) - exp_l) > 1e-5f) return 48; + if (std::fabs(read_sample(stereo_f, out.data(), 1) - exp_r) > 1e-5f) return 49; + } + + // Negative controls: 0 rate, out-of-range rate, 0 channels, unsupported channel count, empty block, null ptr. + if (convert_block({SampleKind::Pcm16, 1, 0}, tone.data(), 480, mono_f, out)) return 50; + if (convert_block(mono16, tone.data(), 480, {SampleKind::Float32, 1, 0}, out)) return 51; + if (convert_block({SampleKind::Pcm16, 1, 999}, tone.data(), 480, mono_f, out)) return 52; + if (convert_block({SampleKind::Pcm16, 1, 500000}, tone.data(), 480, mono_f, out)) return 53; + if (convert_block({SampleKind::Pcm16, 0, 48000}, tone.data(), 480, mono_f, out)) return 54; + if (convert_block(mono16, tone.data(), 480, {SampleKind::Float32, 0, 48000}, out)) return 55; + if (convert_block({SampleKind::Pcm16, 3, 48000}, tone.data(), 120, stereo_f, out)) return 56; + if (convert_block({SampleKind::Pcm16, 9, 48000}, tone.data(), 40, stereo_f, out)) return 57; + if (convert_block(mono16, tone.data(), 0, mono_f, out)) return 58; + if (convert_block(mono16, nullptr, 480, mono_f, out)) return 59; StarvationTimer t; // queue empties at 100 ms, producer resumes at 400 ms, data moves at 430 ms t.sample_queue(50, 10, true); From 054c159dddbff917747b3afa0eec0c538cdcf48c Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:50:04 +0100 Subject: [PATCH 063/775] startup_stubs: prefix navigation-cluster scan codes with E0 --- src/startup_stubs/gameinput.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/startup_stubs/gameinput.cpp b/src/startup_stubs/gameinput.cpp index 0e5663b51..f474cc133 100644 --- a/src/startup_stubs/gameinput.cpp +++ b/src/startup_stubs/gameinput.cpp @@ -194,6 +194,10 @@ std::uint32_t sample_keys(KeyState* out, std::size_t capacity) KeyState ks{}; // _EX keeps the 0xE0/0xE1 prefix, so Left Arrow (0xE04B) differs from keypad 4 (0x4B). ks.scanCode = static_cast(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC_EX)); + // The navigation cluster shares scan codes with keypad keys and is reported unprefixed by some Windows builds. + const bool extended_key = (vk >= VK_PRIOR && vk <= VK_DOWN) || vk == VK_INSERT || vk == VK_DELETE || + vk == VK_DIVIDE || vk == VK_LWIN || vk == VK_RWIN || vk == VK_APPS; + if (extended_key && ks.scanCode != 0 && (ks.scanCode & 0xFF00u) == 0) ks.scanCode |= 0xE000u; const UINT ch = MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR); if ((ch & 0x80000000u) == 0 && (ch & 0xFFFFu) != 0) ks.codePoint = ch & 0xFFFFu; ks.virtualKey = vkey; From daf09b2af2d5a935869b08d25e7452b886f0ad0b Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:50:34 +1000 Subject: [PATCH 064/775] runtime: hand the executable a storage root that ends in a separator and is not cut off The executable appends names to the persistent-local-storage root as it is. With X2W_STORAGE_PATH=D:\saves its settings went to D:\savessettings\settings.xml. The value was also read into a 64-byte buffer. A longer value left the buffer empty, the executable was handed an empty root and created none of its folders. The root now gets a trailing separator when it has none, values up to 258 characters fit, and a longer one is refused with a log line in favour of the default. --- CMakeLists.txt | 8 ++++ docs/startup-runtime.md | 2 +- src/startup_stubs/runtime_proxy.cpp | 19 +++++++- src/startup_stubs/storage_root.h | 29 ++++++++++++ tests/startup_storage_root_check.cpp | 69 ++++++++++++++++++++++++++++ tools/startup/run.ps1 | 2 +- 6 files changed, 125 insertions(+), 4 deletions(-) create mode 100644 src/startup_stubs/storage_root.h create mode 100644 tests/startup_storage_root_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 8acd8f3e7..05d7a7ac7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -630,6 +630,14 @@ target_sources(offscreen_check PRIVATE tests/startup_sampler_x.cpp "${startup_sa target_sources(offscreen_check PRIVATE tests/startup_sampler_heap.cpp) target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp) target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp) +# The storage root handed to the executable ends in a separator and is never cut off +# (src/startup_stubs/storage_root.h); the mutated run is the negative control. +add_executable(startup_storage_root_check tests/startup_storage_root_check.cpp) +target_include_directories(startup_storage_root_check PRIVATE src) +target_compile_features(startup_storage_root_check PRIVATE cxx_std_17) +add_test(NAME startup_storage_root COMMAND startup_storage_root_check) +add_test(NAME startup_storage_root_separator_control COMMAND startup_storage_root_check --mutate separator) +set_tests_properties(startup_storage_root_separator_control PROPERTIES WILL_FAIL TRUE) # Stand-in format for 16-bit packed targets the adapter cannot use (src/startup_stubs/packed_target_format.h). add_executable(startup_packed_target_check tests/startup_packed_target_check.cpp) target_include_directories(startup_packed_target_check PRIVATE src) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9ff8d97c1..39e3c8b87 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -214,7 +214,7 @@ ctest --preset release --no-tests=error -R '^startup_inflate$' -V | `X2W_AUDIO_PERMISSIVE=1` | audio HAL / APU stand-ins accept their calls (no output) | | `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user | -| `X2W_STORAGE_PATH`, `X2W_STORAGE_MB`, `X2W_TITLE_ID` | persistent local storage and the manifest values the runtime would return | +| `X2W_STORAGE_PATH`, `X2W_STORAGE_MB`, `X2W_TITLE_ID` | persistent local storage and the manifest values the runtime would return. The path is handed to the executable with a trailing separator, added when missing, because the executable appends names to it as it is; up to 258 characters, a longer value is refused with a log line and `S:\` is used (`src/startup_stubs/storage_root.h`, `ctest --preset release --no-tests=error -R '^startup_storage_root'`) | | `X2W_INPUT_SCRIPT=mask@sec,...` | timed virtual gamepad presses (0x4 = A); keyboard and XInput pad 0 also work | | `X2W_SAMPLER_HEAP=1` | `gfx2hlsl.py` translates a sampler-heap load with a run-time offset into `SamplerState qh[2048] : register(s0, space1)` and writes `smpheap 2048 1 fallback 2047`. The stand-in uses entries 0 to 2046 for the bound heap and reserves entry 2047 for unaligned or out-of-range offsets. It also accepts the original `smpheap 2048 1` manifest with all 2,048 entries available. [#1143](https://github.com/R0Y00/Xbox2Windows/issues/1143) | | `X2W_XG_VERBOSE=1` | logs every texture layout query with its mip sizes | diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 4817215a2..edafd8d4a 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -10,6 +10,7 @@ #include "startup_stubs/api_trace.h" #include "startup_stubs/local_log.h" #include "startup_stubs/save_store.h" +#include "startup_stubs/storage_root.h" #include #include @@ -703,10 +704,24 @@ bool area_call(unsigned long provider, int slot, u64* args, u64* result) // Persistent local storage: the root of a drive (X2W_STORAGE_PATH, e.g. "S:\\", mapped by the run // script onto a folder outside the game) with the quota from the manifest (X2W_STORAGE_MB). struct StorageObject { void* const* vtable; }; +// The value is read once. It gets a trailing separator when it has none (storage_root.h). A value +// that does not fit is refused with a log line and the default is used: handing the executable a +// cut-off or empty root would send its files somewhere else without a word. const char* storage_path() { - static char path[64]; - if (!path[0] && !GetEnvironmentVariableA("X2W_STORAGE_PATH", path, sizeof(path))) std::strcpy(path, "S:\\"); + static char path[x2w_startup::storage_root_capacity]; + static INIT_ONCE once = INIT_ONCE_STATIC_INIT; + InitOnceExecuteOnce(&once, [](PINIT_ONCE, PVOID, PVOID*) -> BOOL { + char value[x2w_startup::storage_root_capacity + 1]; + const DWORD length = GetEnvironmentVariableA("X2W_STORAGE_PATH", value, sizeof(value)); + if (length >= sizeof(value)) + x2w_local::logf("x2w-runtime X2W_STORAGE_PATH has %lu characters, more than the %zu supported: using S:\\", + static_cast(length - 1), x2w_startup::storage_root_capacity - 2); + else if (length && !x2w_startup::storage_root(value, path)) + x2w_local::logf("x2w-runtime X2W_STORAGE_PATH does not fit with its trailing separator: using S:\\"); + if (!path[0]) std::strcpy(path, "S:\\"); + return TRUE; + }, nullptr, nullptr); return path; } HRESULT __stdcall storage_query(StorageObject* self, const GUID*, void** out) { if (out) *out = self; return S_OK; } diff --git a/src/startup_stubs/storage_root.h b/src/startup_stubs/storage_root.h new file mode 100644 index 000000000..b789a8a92 --- /dev/null +++ b/src/startup_stubs/storage_root.h @@ -0,0 +1,29 @@ +// Experimental (docs/startup-runtime.md): the persistent-local-storage root handed to a console +// executable, made from X2W_STORAGE_PATH. +// +// The executable appends names to the root as it is ("settings\settings.xml", "cloudpers\"), so +// the root must end in a separator: without one, "D:\saves" became "D:\savessettings\settings.xml". +#pragma once + +#include +#include + +namespace x2w_startup { +// The longest root accepted, without the terminating NUL (MAX_PATH - 1, with room for a separator). +constexpr std::size_t storage_root_capacity = 260; + +// Writes `value` with one trailing separator into out[storage_root_capacity]. A value that +// already ends in '\' or '/' is copied as it is. Returns false, leaving out alone, for a null or +// empty value and for one that does not fit with its separator. +inline bool storage_root(const char* value, char* out) +{ + const std::size_t length = value ? std::strlen(value) : 0; + if (!length) return false; + const bool separated = value[length - 1] == '\\' || value[length - 1] == '/'; + if (length + (separated ? 0 : 1) >= storage_root_capacity) return false; + std::memcpy(out, value, length); + if (!separated) out[length] = '\\'; + out[length + (separated ? 0 : 1)] = '\0'; + return true; +} +} // namespace x2w_startup diff --git a/tests/startup_storage_root_check.cpp b/tests/startup_storage_root_check.cpp new file mode 100644 index 000000000..b5df78399 --- /dev/null +++ b/tests/startup_storage_root_check.cpp @@ -0,0 +1,69 @@ +// Checks src/startup_stubs/storage_root.h: the storage root handed to the executable always ends in +// one separator, and a value that does not fit is refused instead of cut off. +// --mutate separator the rule without the appended separator; must fail (negative control) +#include "startup_stubs/storage_root.h" + +#include +#include + +namespace { +int failures; +bool mutate; + +bool root(const char* value, char* out) +{ + if (!mutate) return x2w_startup::storage_root(value, out); + // The behaviour before: the value as it is. + if (!value || !*value || std::strlen(value) >= x2w_startup::storage_root_capacity) return false; + std::strcpy(out, value); + return true; +} + +void expect(const char* name, const char* value, const char* wanted) +{ + char out[x2w_startup::storage_root_capacity + 8]; + std::memset(out, '#', sizeof(out)); + out[sizeof(out) - 1] = '\0'; + const bool ok = root(value, out); + const bool match = wanted ? ok && std::strcmp(out, wanted) == 0 : !ok && out[0] == '#'; + // Nothing may be written past the capacity. + const bool bounded = out[x2w_startup::storage_root_capacity] == '#'; + if (!match || !bounded) { + std::printf("FAIL %s: %s \"%.80s\", expected %s%s\n", name, ok ? "gave" : "refused, buffer", ok ? out : "untouched or not", + wanted ? wanted : "a refusal with the buffer untouched", bounded ? "" : " (wrote past the capacity)"); + ++failures; + } +} +} // namespace + +int main(int argc, char** argv) +{ + mutate = argc == 3 && !std::strcmp(argv[1], "--mutate") && !std::strcmp(argv[2], "separator"); + if (argc != 1 && !mutate) return 2; + // The executable appends "settings\settings.xml" to the root as it is. + expect("drive root", "S:\\", "S:\\"); + expect("folder without a separator", "D:\\saves", "D:\\saves\\"); + expect("folder with a separator", "D:\\saves\\", "D:\\saves\\"); + expect("folder with a forward slash", "D:/saves/", "D:/saves/"); + expect("relative folder", ".", ".\\"); + expect("bare drive", "S:", "S:\\"); + expect("empty value", "", nullptr); + expect("no value", nullptr, nullptr); + // 64 characters was the old buffer: such a value now fits. + const std::string sixty_four = "D:\\" + std::string(60, 'a') + "\\"; + expect("64 characters", sixty_four.c_str(), sixty_four.c_str()); + // The longest values that fit, with and without their own separator, and the first that do not. + const std::size_t capacity = x2w_startup::storage_root_capacity; + const std::string longest_plain(capacity - 2, 'b'), longest_separated = std::string(capacity - 2, 'b') + "\\"; + expect("longest value without a separator", longest_plain.c_str(), longest_separated.c_str()); + expect("longest value with a separator", longest_separated.c_str(), longest_separated.c_str()); + expect("one character too long without a separator", std::string(capacity - 1, 'b').c_str(), nullptr); + expect("one character too long with a separator", (std::string(capacity - 1, 'b') + "\\").c_str(), nullptr); + expect("far too long", std::string(4 * capacity, 'b').c_str(), nullptr); + if (failures) { + std::printf("startup_storage_root: %d FAILED\n", failures); + return 1; + } + std::printf("startup_storage_root: PASS (9 roots, 5 refusals)\n"); + return 0; +} diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index dc629f58b..0f25b6ceb 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -20,7 +20,7 @@ param( [int]$MemoryGiB = 14, [int]$ContinueAsserts = 0, # main-image int3s to log and step over (title soft asserts) [string]$InputScript = "", # X2W_INPUT_SCRIPT, e.g. "4@70" = A at 70 s - [string]$StoragePath = "", # X2W_STORAGE_PATH: persistent local storage root + [string]$StoragePath = "", # X2W_STORAGE_PATH: persistent local storage root (a trailing \ is added when missing) [string]$ShaderCache = "out/startup/shader_cache", [switch]$Render, # draw through translated pipelines [switch]$FakeUser, # answer the user API for one local user From 3fcfd9ff00580e629dd1f78568f5665c65640e45 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:51:18 +0800 Subject: [PATCH 065/775] docs: record the mesh draw fallback on Intel Xe2 The mesh draw fallback paragraph lists the GTX 1060, in-box WARP and app-local WARP. Add the Intel Arc 140T at 41c0852c: 128 export bytes and 1,024 pixels matched in each baseline draw, and the three controls reproduced their recorded signature - zero pixel differences for the changed guard, 276 for the collapsed index and 992 for the stale palette with matching exports. Zero debug errors and warnings. Docs only. --- docs/experiments.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index c783e3cad..590b0a5f7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2551,7 +2551,11 @@ pixel differences, and a stale palette with 992 pixel differences and matching exports. DXC 1.9.2602.17 compiled all stages at Shader Model 6.0. The debug layer reported zero errors and warnings. All seven native and fallback mesh tests also passed on app-local WARP 1.0.22 -with Agility SDK 1.620.2. +with Agility SDK 1.620.2. On Windows 11 build 26300.9974, the Intel Arc 140T +(32.0.101.8132) matched the same 128 export bytes and 1,024 pixels in each +baseline draw and reproduced all three controls: the changed guard kept zero +pixel differences, the collapsed index produced 276 and the stale palette 992 +with matching exports. The debug layer reported zero errors and warnings. This fallback covers the single-group specialization below. The supported shape has three vertices, one triangle and optional PARAM0. The hardware's From bf51223477c009857221de2e759f4b75fcebcf03 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:51:21 +0100 Subject: [PATCH 066/775] d3d12_xs: support buffer and RT-AS memory SRVs on slot 70 --- CMakeLists.txt | 9 ++ docs/startup-runtime.md | 23 ++++ src/startup_stubs/d3d12_memory_srv.inl | 81 +++++++++++ src/startup_stubs/memory_srv_buffer.h | 160 ++++++++++++++++++++++ tests/startup_address_buffer_srv_check.py | 59 ++++++++ tests/startup_address_srv.cpp | 99 +++++++++++++ tests/startup_address_srv_check.py | 2 +- tests/startup_memory_srv_buffer_check.cpp | 153 +++++++++++++++++++++ tests/startup_stream_draw.cpp | 3 + 9 files changed, 588 insertions(+), 1 deletion(-) create mode 100644 src/startup_stubs/memory_srv_buffer.h create mode 100644 tests/startup_address_buffer_srv_check.py create mode 100644 tests/startup_memory_srv_buffer_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f61af885..24dc86b61 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -655,6 +655,11 @@ endforeach() add_test(NAME startup_present_view_srgb_control COMMAND startup_present_view_check warp --mutate srgb) set_tests_properties(startup_present_view_identity_control startup_present_view_srgb_control PROPERTIES WILL_FAIL TRUE) set_tests_properties(startup_present_view_hardware PROPERTIES SKIP_RETURN_CODE 77) +# Buffer and raytracing acceleration-structure memory SRV validation (src/startup_stubs/memory_srv_buffer.h). +add_executable(startup_memory_srv_buffer_check tests/startup_memory_srv_buffer_check.cpp) +target_include_directories(startup_memory_srv_buffer_check PRIVATE src) +target_compile_features(startup_memory_srv_buffer_check PRIVATE cxx_std_17) +add_test(NAME startup_memory_srv_buffer COMMAND startup_memory_srv_buffer_check) # Console allocation sizes for depth-with-stencil and multisampled textures # (src/startup_stubs/console_plane_size.h); the mutated run is the negative control. add_executable(startup_plane_size_check tests/startup_plane_size_check.cpp) @@ -1467,6 +1472,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_srv_check.py" "$" "${backend}") set_tests_properties(startup_address_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_address_buffer_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_buffer_srv_check.py" + "$" "${backend}") + set_tests_properties(startup_address_buffer_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_placed_vertex_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_placed_vertex_check.py" "$" "${backend}") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9ff8d97c1..d8e4bab45 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -700,3 +700,26 @@ is not affected: section-backed pages already took the committed, not-aliased pa - `ctest --preset release --no-tests=error -R '^xmem_page_runs_device_' -V` places a buffer (slot 133) inside one view and across three kinds of boundary: two mapping calls, two backing sections, and single-page views. + +## Buffer and raytracing acceleration-structure memory SRVs (device slot 70) + +Device slot 70 (`src/startup_stubs/d3d12_memory_srv.inl`, validation in +`src/startup_stubs/memory_srv_buffer.h`) also accepts `D3D12_RESOURCE_DIMENSION_BUFFER` +descriptions with: + +- `D3D12_SRV_DIMENSION_BUFFER` (raw `R32_TYPELESS`, structured `Format == UNKNOWN` with stride up to + 2048, or typed buffers). It resolves an existing live placed (slot 133) or committed (slot 127) + buffer covering `[address, address + (FirstElement + NumElements) * element_bytes)`, checks + alignment and bounds, adjusts `FirstElement` by `(address - base) / element_bytes`, and forwards + to `CreateShaderResourceView` (slot 18). +- `D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE` (`Format == UNKNOWN`). When the adapter + reports raytracing support (`D3D12_FEATURE_D3D12_OPTIONS5::RaytracingTier != NOT_SUPPORTED`), it + resolves the buffer at `address`, verifies 256-byte alignment on both the title address and the + resolved desktop GPU virtual address, sets `RaytracingAccelerationStructure.Location`, and + forwards to slot 18 with `pResource == nullptr`. Adapters without raytracing support refuse the + call cleanly (`raytracing_unsupported`) without removing the device. + +Checks: + +- `ctest --preset release --no-tests=error -R '^startup_memory_srv_(report|buffer)$' -V` +- `ctest --preset release --no-tests=error -R '^startup_address_(srv|buffer_srv)_' -V` diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 2e7202598..f457b8cbc 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -1,4 +1,6 @@ // Included after the resource creation and descriptor handlers. +#include "memory_srv_buffer.h" + struct MemoryShaderResourceView { D3D12_SHADER_RESOURCE_VIEW_DESC view; u64 address; @@ -24,6 +26,8 @@ bool tiled_bc_srv(const D3D12_RESOURCE_DESC& r) bool supports_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) { + if (r.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) + return x2w_startup::supports_buffer_memory_srv(r, v); if (x2w_startup::bc64::supports(r)) { if (v.Format != r.Format || v.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) return false; @@ -83,6 +87,41 @@ Wrapper* existing_memory_texture(u64 address, const D3D12_RESOURCE_DESC& desc) return match; } +Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) +{ + if (!address || !bytes) return nullptr; + const auto placed = placed_buffer_range(device, address, bytes); + if (placed.reject) return nullptr; + if (placed.owner) { + if (InterlockedCompareExchange(&placed.owner->own().refs, 0, 0) <= 0) return nullptr; + const auto* info = resource_info(placed.owner); + if (!info || info->console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + (info->console.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) + return nullptr; + return const_cast(placed.owner); + } + Wrapper* match = nullptr; + AcquireSRWLockShared(¬e_lock); + for (const auto& [wrapper, info] : resource_infos()) { + if (info.placement != Placement::none || + info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + (info.console.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || + InterlockedCompareExchange(&wrapper->own().refs, 0, 0) <= 0) + continue; + const u64 base = reinterpret_cast(wrapper->own().title_memory); + const u64 width = info.console.Width; + if (!base || address < base || address - base >= width || bytes > width - (address - base)) + continue; + if (match) { + match = nullptr; + break; + } + match = const_cast(wrapper); + } + ReleaseSRWLockShared(¬e_lock); + return match; +} + // Keep metadata for published tiled SRVs; allocate GPU memory only when a // translated draw actually samples one. A later write to the same address is // picked up by the uploader even when the description and view token are reused. @@ -176,6 +215,48 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou if (first_calls(refused, 8)) log_refused_memory_srv("unsupported memory SRV arguments", reason, resource, input, destination); return; } + if (resource->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + if (static_cast(input->view.ViewDimension) == x2w_startup::srv_dimension_rt_acceleration_structure) { + D3D12_FEATURE_DATA_D3D12_OPTIONS5 opts5{}; + if (FAILED(device_of(self)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &opts5, sizeof(opts5))) || + opts5.RaytracingTier == D3D12_RAYTRACING_TIER_NOT_SUPPORTED) { + if (first_calls(refused, 8)) + log_refused_memory_srv("raytracing acceleration structure views are not supported on this adapter", + "raytracing_unsupported", resource, input, destination); + return; + } + Wrapper* buffer = existing_memory_buffer(self, input->address, resource->Width); + const ResourceInfo* info = buffer ? resource_info(buffer) : nullptr; + auto* desktop_res = buffer ? static_cast(buffer->own().real) : nullptr; + D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; + if (!buffer || !info || !desktop_res || + !x2w_startup::resolve_rt_as_srv_desc(reinterpret_cast(buffer->own().title_memory), + info->console.Width, desktop_res->GetGPUVirtualAddress(), + input->address, resource->Width, input->view, adjusted)) { + if (first_calls(refused, 8)) + log_refused_memory_srv("unavailable buffer at the supplied address", "buffer_unavailable", + resource, input, destination); + return; + } + view_slot<18, 2>(self, 0, reinterpret_cast(&adjusted), destination, 0); + return; + } + const u64 elem_bytes = x2w_startup::buffer_srv_element_bytes(input->view); + const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; + Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); + const ResourceInfo* info = buffer ? resource_info(buffer) : nullptr; + D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; + if (!buffer || !info || + !x2w_startup::resolve_buffer_srv_desc(reinterpret_cast(buffer->own().title_memory), + info->console.Width, input->address, input->view, adjusted)) { + if (first_calls(refused, 8)) + log_refused_memory_srv("unavailable buffer at the supplied address", "buffer_unavailable", + resource, input, destination); + return; + } + view_slot<18, 2>(self, reinterpret_cast(buffer), reinterpret_cast(&adjusted), destination, 0); + return; + } Wrapper* texture = (tiled_bc_srv(*resource) || x2w_startup::bc64::supports(*resource)) ? publish_tiled_texture(self, input->address, *resource) : existing_memory_texture(input->address, *resource); if (!texture) { diff --git a/src/startup_stubs/memory_srv_buffer.h b/src/startup_stubs/memory_srv_buffer.h new file mode 100644 index 000000000..70e3e193a --- /dev/null +++ b/src/startup_stubs/memory_srv_buffer.h @@ -0,0 +1,160 @@ +// Pure validation and offset/GPU-address resolution for buffer and raytracing +// acceleration-structure memory SRVs (device slot 70). +#pragma once + +#include + +#include + +namespace x2w_startup { + +constexpr std::uint32_t srv_dimension_rt_acceleration_structure = 11; + +// Byte size of a single element for typed buffer SRVs; 0 when unknown or invalid for typed buffers. +inline std::uint32_t typed_buffer_format_bytes(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_UINT: + case DXGI_FORMAT_R32G32B32A32_SINT: + return 16; + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: + return 12; + case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: + case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32_SINT: + return 8; + case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R11G11B10_FLOAT: + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: + case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: + case DXGI_FORMAT_B8G8R8X8_UNORM: + case DXGI_FORMAT_R16G16_FLOAT: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SNORM: + case DXGI_FORMAT_R16G16_SINT: + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32_SINT: + return 4; + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R8G8_SINT: + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16_SNORM: + case DXGI_FORMAT_R16_SINT: + return 2; + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: + case DXGI_FORMAT_R8_SINT: + return 1; + default: + return 0; + } +} + +inline bool valid_buffer_resource_desc(const D3D12_RESOURCE_DESC& r) +{ + return r.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && r.Width > 0 && r.Height == 1 && + r.DepthOrArraySize == 1 && r.MipLevels == 1 && r.Format == DXGI_FORMAT_UNKNOWN && + r.SampleDesc.Count == 1 && r.SampleDesc.Quality == 0 && + r.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR && + (r.Alignment == 0 || r.Alignment == D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) && + !(r.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); +} + +inline std::uint32_t buffer_srv_element_bytes(const D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + if (v.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || + v.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING || + v.Buffer.NumElements == 0) + return 0; + const UINT flags = static_cast(v.Buffer.Flags); + if (flags & ~static_cast(D3D12_BUFFER_SRV_FLAG_RAW)) return 0; + if (flags == D3D12_BUFFER_SRV_FLAG_RAW) { + if (v.Format != DXGI_FORMAT_R32_TYPELESS || v.Buffer.StructureByteStride != 0) return 0; + return 4; + } + if (v.Buffer.StructureByteStride != 0) { + if (v.Format != DXGI_FORMAT_UNKNOWN || v.Buffer.StructureByteStride > 2048) return 0; + return v.Buffer.StructureByteStride; + } + return typed_buffer_format_bytes(v.Format); +} + +inline bool supports_buffer_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + if (!valid_buffer_resource_desc(r)) return false; + if (static_cast(v.ViewDimension) == srv_dimension_rt_acceleration_structure) { + return v.Format == DXGI_FORMAT_UNKNOWN && + v.Shader4ComponentMapping == D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + } + const std::uint32_t elem_bytes = buffer_srv_element_bytes(v); + if (!elem_bytes) return false; + const std::uint64_t total_elements = r.Width / elem_bytes; + return v.Buffer.FirstElement <= total_elements && + v.Buffer.NumElements <= total_elements - v.Buffer.FirstElement; +} + +inline bool resolve_buffer_srv_desc(std::uint64_t buffer_title_base, std::uint64_t buffer_width, + std::uint64_t address, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, + D3D12_SHADER_RESOURCE_VIEW_DESC& resolved) +{ + const std::uint32_t elem_bytes = buffer_srv_element_bytes(view); + if (!elem_bytes || !buffer_title_base || address < buffer_title_base) return false; + const std::uint64_t offset = address - buffer_title_base; + if (offset >= buffer_width || offset % elem_bytes != 0) return false; + const std::uint64_t avail_elements = (buffer_width - offset) / elem_bytes; + if (view.Buffer.FirstElement > avail_elements || + view.Buffer.NumElements > avail_elements - view.Buffer.FirstElement) + return false; + const std::uint64_t adjusted_first = view.Buffer.FirstElement + offset / elem_bytes; + if (view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_RAW && + (adjusted_first * elem_bytes) % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT != 0) + return false; + resolved = view; + resolved.Buffer.FirstElement = adjusted_first; + return true; +} + +inline bool resolve_rt_as_srv_desc(std::uint64_t buffer_title_base, std::uint64_t buffer_width, + D3D12_GPU_VIRTUAL_ADDRESS buffer_gpu_base, std::uint64_t address, + std::uint64_t view_width, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, + D3D12_SHADER_RESOURCE_VIEW_DESC& resolved) +{ + constexpr std::uint64_t alignment = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT; + if (static_cast(view.ViewDimension) != srv_dimension_rt_acceleration_structure || + view.Format != DXGI_FORMAT_UNKNOWN || + view.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) + return false; + if (!buffer_title_base || !buffer_gpu_base || address < buffer_title_base || !view_width) return false; + if (address % alignment != 0) return false; + const std::uint64_t offset = address - buffer_title_base; + if (offset >= buffer_width || view_width > buffer_width - offset) return false; + if (offset > UINT64_MAX - buffer_gpu_base) return false; + const D3D12_GPU_VIRTUAL_ADDRESS gpu_location = buffer_gpu_base + offset; + if (gpu_location % alignment != 0) return false; + resolved = view; + resolved.RaytracingAccelerationStructure.Location = gpu_location; + return true; +} + +} // namespace x2w_startup diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py new file mode 100644 index 000000000..094b2b183 --- /dev/null +++ b/tests/startup_address_buffer_srv_check.py @@ -0,0 +1,59 @@ +"""Publish placed buffer SRVs by address, sample them in translated draws, and check refusals.""" +from pathlib import Path +import re +import sys +import tempfile + +from startup_address_srv_check import draw_texture + +HEX = r"0x[0-9a-f]+" + + +def check_refusal_lines(log): + prefix = r"x2w-d3d12 Device::slot70 " + expected = [ + prefix + + r"unavailable buffer at the supplied address: reason=buffer_unavailable " + + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " + + r"view\{dim=1 fmt=62 map=0x1688 first=0 count=4 stride=0 flags=0x1 \(buffer views are not supported\)\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + ] + lines = [line.rstrip() for line in log.splitlines() if "Device::slot70" in line] + if len(lines) != len(expected): + raise AssertionError(f"{len(lines)} slot 70 lines, expected {len(expected)}:\n" + "\n".join(lines)) + for line, pattern in zip(lines, expected): + if not re.fullmatch(pattern, line): + raise AssertionError(f"slot 70 line does not match\n line {line}\n expected {pattern}") + + +def check(directory, consumer, backend): + hlsl = ( + "ByteAddressBuffer b : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " return float4(float(b.Load(0)) / 255.0, 0, 0, 1);\n" + "}\n" + ) + trap_log = directory / "trap.log" + actual = draw_texture( + directory, + consumer, + backend, + hlsl, + {"X2W_TEST_ADDRESS_BUFFER_SRV": "1", "X2W_TRAP_LOG": str(trap_log)}, + binding="srv 0 buf table 0 0", + ) + if actual is None: + return 77 + values = (17, 63, 141, 141, 99, 17, 17, 17) + row = b"".join(bytes((v, 0, 0, 255)) for v in values) + expected = row * 4 + if actual != expected: + raise AssertionError(f"actual {actual.hex()} expected {expected.hex()}") + check_refusal_lines(trap_log.read_text(errors="replace")) + print(f"{backend}: buffer memory SRV (raw base, raw interior, structured, refused unaligned) exact") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index cf2f28b6b..38876f0b4 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -243,3 +243,102 @@ void release_placed_vertices(bool done) p.resource[0] = nullptr; } } + +int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) +{ + alignas(65536) static std::array buf0{}; + alignas(65536) static std::array buf1{}; + buf0.fill(0); + buf1.fill(0); + buf0[0] = 17; + buf0[1] = 99; + buf0[4] = 63; + buf1[4] = 141; + + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 256; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + + void* placed[2]{}; + if (FAILED(static_cast(invoke(guest, 133, ptr(buf0.data()), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed[0]))))) return 47; + if (FAILED(static_cast(invoke(guest, 133, ptr(buf1.data()), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed[1]))))) return 47; + + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + + const auto draw = [&](LONG x) { + const D3D12_RECT strip{x, 0, x + 1, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + }; + + ViewAt raw{}; + raw.view.Format = DXGI_FORMAT_R32_TYPELESS; + raw.view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + raw.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + raw.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + raw.view.Buffer.NumElements = 4; + + raw.address = ptr(buf0.data()); + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); + draw(0); + + raw.address = ptr(buf0.data() + 4); + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); + draw(1); + + raw.address = ptr(buf1.data()); + raw.view.Buffer.FirstElement = 4; + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); + draw(2); + + // Unaligned interior address for a raw buffer must be refused and keep the previous descriptor. + raw.view.Buffer.FirstElement = 0; + raw.address = ptr(buf0.data() + 1); + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); + draw(3); + + ViewAt structured{}; + structured.view.Format = DXGI_FORMAT_UNKNOWN; + structured.view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + structured.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + structured.view.Buffer.FirstElement = 1; + structured.view.Buffer.NumElements = 1; + structured.view.Buffer.StructureByteStride = 4; + structured.address = ptr(buf0.data()); + invoke(guest, 70, ptr(&desc), ptr(&structured), cpu); + draw(4); + + // Exercise RT acceleration-structure memory SRV when the adapter supports raytracing. + D3D12_FEATURE_DATA_D3D12_OPTIONS5 opts5{}; + if (SUCCEEDED(desktop->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &opts5, sizeof(opts5))) && + opts5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED) { + alignas(65536) static std::array as_mem{}; + D3D12_RESOURCE_DESC as_desc = desc; + as_desc.Width = as_mem.size(); + as_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + void* as_res = nullptr; + if (FAILED(static_cast(invoke(guest, 133, ptr(as_mem.data()), ptr(&as_desc), + D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, 0, + ptr(&__uuidof(ID3D12Resource)), ptr(&as_res))))) return 48; + ViewAt as_view{}; + as_view.view.Format = DXGI_FORMAT_UNKNOWN; + as_view.view.ViewDimension = static_cast(11); + as_view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + as_view.address = ptr(as_mem.data()); + invoke(guest, 70, ptr(&as_desc), ptr(&as_view), cpu); + if (FAILED(desktop->GetDeviceRemovedReason())) return 49; + } + + raw.address = ptr(buf0.data()); + raw.view.Buffer.FirstElement = 0; + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); + draw(5); + draw(6); + draw(7); + return 0; +} diff --git a/tests/startup_address_srv_check.py b/tests/startup_address_srv_check.py index 62a3a5855..a5a6cc5c3 100644 --- a/tests/startup_address_srv_check.py +++ b/tests/startup_address_srv_check.py @@ -58,7 +58,7 @@ def check_refusal_lines(log): + " " + R8_VIEW + rf" dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", prefix + r"unavailable texture at the supplied base and layout: reason=texture_unavailable " + R8_RESOURCE % 2 + " " + R8_VIEW + rf" dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", - prefix + r"unsupported memory SRV arguments: reason=unsupported_description " + prefix + r"unavailable buffer at the supplied address: reason=buffer_unavailable " + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " + r"view\{dim=1 fmt=0 map=0x1688 first=0 count=64 stride=4 flags=0x0 \(buffer views are not supported\)\} " + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", diff --git a/tests/startup_memory_srv_buffer_check.cpp b/tests/startup_memory_srv_buffer_check.cpp new file mode 100644 index 000000000..9cbbbbe90 --- /dev/null +++ b/tests/startup_memory_srv_buffer_check.cpp @@ -0,0 +1,153 @@ +// Checks validation, offset/element adjustment, and GPU virtual address resolution for +// buffer and raytracing acceleration-structure memory SRVs without a device. +#include "startup_stubs/memory_srv_buffer.h" + +#include + +namespace { + +int failures; + +void check(const char* name, bool condition) +{ + if (condition) return; + ++failures; + std::printf("FAIL %s\n", name); +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 width) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = width; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +D3D12_SHADER_RESOURCE_VIEW_DESC raw_view(UINT64 first_element, UINT num_elements) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.FirstElement = first_element; + v.Buffer.NumElements = num_elements; + v.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + return v; +} + +D3D12_SHADER_RESOURCE_VIEW_DESC structured_view(UINT64 first_element, UINT num_elements, UINT stride) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_UNKNOWN; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.FirstElement = first_element; + v.Buffer.NumElements = num_elements; + v.Buffer.StructureByteStride = stride; + return v; +} + +D3D12_SHADER_RESOURCE_VIEW_DESC typed_view(DXGI_FORMAT format, UINT64 first_element, UINT num_elements) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = format; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Buffer.FirstElement = first_element; + v.Buffer.NumElements = num_elements; + return v; +} + +D3D12_SHADER_RESOURCE_VIEW_DESC rt_as_view(DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = format; + v.ViewDimension = static_cast(x2w_startup::srv_dimension_rt_acceleration_structure); + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + return v; +} + +} // namespace + +int main() +{ + const auto buf = buffer_desc(1024); + + // Raw buffer SRV validation and interior offset resolution. + const auto raw_ok = raw_view(4, 16); + check("raw valid", x2w_startup::supports_buffer_memory_srv(buf, raw_ok)); + auto raw_bad_fmt = raw_ok; + raw_bad_fmt.Format = DXGI_FORMAT_R32_FLOAT; + check("raw bad format", !x2w_startup::supports_buffer_memory_srv(buf, raw_bad_fmt)); + auto raw_bad_stride = raw_ok; + raw_bad_stride.Buffer.StructureByteStride = 4; + check("raw nonzero stride", !x2w_startup::supports_buffer_memory_srv(buf, raw_bad_stride)); + check("raw zero count", !x2w_startup::supports_buffer_memory_srv(buf, raw_view(0, 0))); + check("raw oob", !x2w_startup::supports_buffer_memory_srv(buf, raw_view(250, 10))); + + D3D12_SHADER_RESOURCE_VIEW_DESC resolved{}; + check("raw resolve base", x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x10000, raw_ok, resolved) && + resolved.Buffer.FirstElement == 4 && resolved.Buffer.NumElements == 16); + check("raw resolve interior 16B", + x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x10010, raw_ok, resolved) && + resolved.Buffer.FirstElement == 8); + check("raw resolve unaligned 4B", + !x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x10004, raw_view(0, 4), resolved)); + check("raw resolve oob", + !x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x103e0, raw_view(0, 16), resolved)); + + // Structured buffer SRV validation and interior offset resolution. + const auto str_ok = structured_view(2, 8, 16); + check("structured valid", x2w_startup::supports_buffer_memory_srv(buf, str_ok)); + auto str_bad_fmt = str_ok; + str_bad_fmt.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + check("structured bad format", !x2w_startup::supports_buffer_memory_srv(buf, str_bad_fmt)); + check("structured stride too large", !x2w_startup::supports_buffer_memory_srv(buf, structured_view(0, 1, 2052))); + check("structured resolve interior", + x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x10020, str_ok, resolved) && + resolved.Buffer.FirstElement == 4); + check("structured resolve unaligned", + !x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x10008, str_ok, resolved)); + + // Typed buffer SRV validation and interior offset resolution. + const auto typ_ok = typed_view(DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 4); + check("typed valid", x2w_startup::supports_buffer_memory_srv(buf, typ_ok)); + check("typed unknown format", !x2w_startup::supports_buffer_memory_srv(buf, typed_view(DXGI_FORMAT_UNKNOWN, 0, 1))); + check("typed resolve interior", + x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x10010, typ_ok, resolved) && + resolved.Buffer.FirstElement == 2); + check("typed resolve unaligned", + !x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x10004, typ_ok, resolved)); + + // Denied shader resource flag on buffer resource. + auto denied_buf = buf; + denied_buf.Flags = D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; + check("denied srv flag", !x2w_startup::supports_buffer_memory_srv(denied_buf, raw_ok)); + + // Raytracing acceleration structure SRV validation and GPU VA mapping. + const auto as_ok = rt_as_view(); + check("rt as valid", x2w_startup::supports_buffer_memory_srv(buf, as_ok)); + check("rt as bad format", !x2w_startup::supports_buffer_memory_srv(buf, rt_as_view(DXGI_FORMAT_R32_TYPELESS))); + check("rt as resolve base", + x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000000ull, 0x10000, 256, as_ok, resolved) && + resolved.RaytracingAccelerationStructure.Location == 0x80000000ull); + check("rt as resolve aligned interior", + x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000000ull, 0x10100, 256, as_ok, resolved) && + resolved.RaytracingAccelerationStructure.Location == 0x80000100ull); + check("rt as unaligned address", + !x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000000ull, 0x10080, 256, as_ok, resolved)); + check("rt as unaligned gpu base", + !x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000080ull, 0x10000, 256, as_ok, resolved)); + check("rt as oob", + !x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000000ull, 0x10300, 512, as_ok, resolved)); + + if (failures) return 1; + std::printf("slot 70 buffer and rt-as memory SRV validation: all checks passed\n"); + return 0; +} diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index c7b056099..d9d55249a 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -269,6 +269,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_SRV", nullptr, 0)) { extern int draw_address_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_srvs(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0)) { + extern int draw_address_buffer_srvs(ID3D12Device*, void*, void*); + if (const int result = draw_address_buffer_srvs(desktop.Get(), guest, list)) return result; } else { if (bc7 && bc7->packed) invoke(list, 52, binding.rtv, arg(packed_clear)); // render into the texture, then sample it if (bc7) invoke(list, 36, 0, binding.table); From 5187d4dc0cddcc768b7144231300a4e68bb9ad33 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:53:00 +0100 Subject: [PATCH 067/775] d3d12_xs: fix namespace include and MSVC alignment in buffer SRV test --- src/startup_stubs/d3d12_memory_srv.inl | 2 -- src/startup_stubs/d3d12_xs_device.cpp | 1 + tests/startup_address_srv.cpp | 35 ++++++++++++++------------ 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index f457b8cbc..4d3287238 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -1,6 +1,4 @@ // Included after the resource creation and descriptor handlers. -#include "memory_srv_buffer.h" - struct MemoryShaderResourceView { D3D12_SHADER_RESOURCE_VIEW_DESC view; u64 address; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 90f86ae7a..dcc66dab3 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -25,6 +25,7 @@ #include "startup_stubs/placement_publish.h" #include "startup_stubs/placed_build.h" #include "startup_stubs/memory_srv_report.h" +#include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/slice_footprints.h" diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 38876f0b4..588c44b40 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -246,10 +246,12 @@ void release_placed_vertices(bool done) int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) { - alignas(65536) static std::array buf0{}; - alignas(65536) static std::array buf1{}; - buf0.fill(0); - buf1.fill(0); + static std::array raw_buf0{}; + static std::array raw_buf1{}; + auto* const buf0 = reinterpret_cast((ptr(raw_buf0.data()) + 0xffff) & ~Word{0xffff}); + auto* const buf1 = reinterpret_cast((ptr(raw_buf1.data()) + 0xffff) & ~Word{0xffff}); + std::memset(buf0, 0, 256); + std::memset(buf1, 0, 256); buf0[0] = 17; buf0[1] = 99; buf0[4] = 63; @@ -262,9 +264,9 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; void* placed[2]{}; - if (FAILED(static_cast(invoke(guest, 133, ptr(buf0.data()), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + if (FAILED(static_cast(invoke(guest, 133, ptr(buf0), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed[0]))))) return 47; - if (FAILED(static_cast(invoke(guest, 133, ptr(buf1.data()), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + if (FAILED(static_cast(invoke(guest, 133, ptr(buf1), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed[1]))))) return 47; Word cpu = 0; @@ -283,22 +285,22 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) raw.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; raw.view.Buffer.NumElements = 4; - raw.address = ptr(buf0.data()); + raw.address = ptr(buf0); invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(0); - raw.address = ptr(buf0.data() + 4); + raw.address = ptr(buf0 + 4); invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(1); - raw.address = ptr(buf1.data()); + raw.address = ptr(buf1); raw.view.Buffer.FirstElement = 4; invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(2); // Unaligned interior address for a raw buffer must be refused and keep the previous descriptor. raw.view.Buffer.FirstElement = 0; - raw.address = ptr(buf0.data() + 1); + raw.address = ptr(buf0 + 1); invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(3); @@ -309,7 +311,7 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) structured.view.Buffer.FirstElement = 1; structured.view.Buffer.NumElements = 1; structured.view.Buffer.StructureByteStride = 4; - structured.address = ptr(buf0.data()); + structured.address = ptr(buf0); invoke(guest, 70, ptr(&desc), ptr(&structured), cpu); draw(4); @@ -317,24 +319,25 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) D3D12_FEATURE_DATA_D3D12_OPTIONS5 opts5{}; if (SUCCEEDED(desktop->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &opts5, sizeof(opts5))) && opts5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED) { - alignas(65536) static std::array as_mem{}; + static std::array raw_as_mem{}; + auto* const as_mem = reinterpret_cast((ptr(raw_as_mem.data()) + 0xffff) & ~Word{0xffff}); D3D12_RESOURCE_DESC as_desc = desc; - as_desc.Width = as_mem.size(); + as_desc.Width = 512; as_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; void* as_res = nullptr; - if (FAILED(static_cast(invoke(guest, 133, ptr(as_mem.data()), ptr(&as_desc), + if (FAILED(static_cast(invoke(guest, 133, ptr(as_mem), ptr(&as_desc), D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, 0, ptr(&__uuidof(ID3D12Resource)), ptr(&as_res))))) return 48; ViewAt as_view{}; as_view.view.Format = DXGI_FORMAT_UNKNOWN; as_view.view.ViewDimension = static_cast(11); as_view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - as_view.address = ptr(as_mem.data()); + as_view.address = ptr(as_mem); invoke(guest, 70, ptr(&as_desc), ptr(&as_view), cpu); if (FAILED(desktop->GetDeviceRemovedReason())) return 49; } - raw.address = ptr(buf0.data()); + raw.address = ptr(buf0); raw.view.Buffer.FirstElement = 0; invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(5); From c4e6f4e6bcff477e91def6c715cf419e06c98044 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:53:09 +0100 Subject: [PATCH 068/775] startup_stubs: stand in for B5G6R5 and array packed render targets Extends the packed render-target stand-in to B5G6R5_UNORM and to 2D arrays of 2 to 2048 slices (a cube map is six). Zero slices, more than 2048, 3D and multisampled stay refused. The device-free check covers the new rows and four mutated runs that must fail. --- CMakeLists.txt | 4 + docs/experiments.md | 8 ++ docs/startup-runtime.md | 23 +++-- src/startup_stubs/packed_target_format.h | 18 +++- tests/startup_packed_target_check.cpp | 112 +++++++++++++++++++--- tests/startup_packed_target_draw_check.py | 13 ++- 6 files changed, 143 insertions(+), 35 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f61af885..ea00a1329 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -635,6 +635,10 @@ add_executable(startup_packed_target_check tests/startup_packed_target_check.cpp target_include_directories(startup_packed_target_check PRIVATE src) target_compile_features(startup_packed_target_check PRIVATE cxx_std_17) add_test(NAME startup_packed_target COMMAND startup_packed_target_check) +foreach(mutation IN ITEMS stand-in array b565 view) + add_test(NAME startup_packed_target_${mutation}_control COMMAND startup_packed_target_check --mutate ${mutation}) + set_tests_properties(startup_packed_target_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() # Diagnostic line for a refused device slot 70 call (src/startup_stubs/memory_srv_report.h). add_executable(startup_memory_srv_report_check tests/startup_memory_srv_report_check.cpp) target_include_directories(startup_memory_srv_report_check PRIVATE src) diff --git a/docs/experiments.md b/docs/experiments.md index c783e3cad..8482a5d19 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -45,6 +45,14 @@ back all 306 current pixels. Suppressing the refresh on the second rotation leav ctest --preset dev --no-tests=error -R '^startup_r8_uint_(warp|hardware)$' -V ``` +## Packed render targets: 5-6-5 and arrays + +`packed_target_stand_in` now also covers B5G6R5_UNORM and 2D arrays of 2 to 2048 slices (a cube map is six). When the adapter lacks render-target (or typed UAV) support for the packed format and has it for R8G8B8A8_UNORM, the texture is created as R8G8B8A8_UNORM with the same slice and mip counts. Zero slices, more than 2048, 3D, buffers and multisampled textures keep their format. The stand-in has 8 bits a channel and an alpha channel that B5G6R5 lacks. Texels the executable writes in the 16-bit layout are not converted. The device-free check covers 61 rows against adapters described by their support bits, and four mutated runs (wrong stand-in format, arrays left alone, B5G6R5 left alone, view kept packed) must fail. The WARP and hardware readback draws a B5G6R5 target; an array target is not drawn. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_packed_target' -V +``` + ## Counted cache-line zero loops `cpu_switch_aot.py` accepts the three-byte CLZERO with full-width RAX addressing for 64-byte guest cache lines. A translated instruction zeroes the aligned line containing RAX. It preserves RAX and flags. The original function controls advancement and termination with ADD, CMP and JB. The supported memory domain is ordinary writable host-backed storage; this test checks final memory, registers and conditions on a single thread. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9ff8d97c1..76763ad90 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -40,15 +40,16 @@ directory to exercise both slots on hardware and WARP. ## 16-bit packed targets -A description that asks for a B5G5R5A1_UNORM or B4G4R4A4_UNORM render target is created as +A description that asks for a B5G5R5A1_UNORM, B4G4R4A4_UNORM or B5G6R5_UNORM render target is created as R8G8B8A8_UNORM when the adapter lacks that use for the packed format and has it for R8G8B8A8_UNORM (`src/startup_stubs/packed_target_format.h`). Without this the description is refused, its allocation-info answer is all ones and the executable gets no texture. The first four stand-ins are logged. -The rule covers the roles that were measured and nothing else: a single-sample 2D texture with -one array slice that is a render target, alone or with unordered access. Other dimensions, -arrays, multisampled textures and textures without the render-target flag keep their format. +The rule covers a single-sample 2D texture or 2D array (2 to 2048 slices; a cube map is six) that is +a render target, alone or with unordered access. Only the format changes: slice count, mip count +and the view dimensions are kept. Other dimensions, zero or more than 2048 slices, multisampled +textures and textures without the render-target flag keep their format. A stand-in texture carries the format it was asked for as private data. A view that names that format on that texture is created as R8G8B8A8_UNORM, both when the executable creates the view @@ -65,17 +66,23 @@ Limits: - CPU-authored texels. Data the executable writes or reads itself in the 16-bit layout (uploads, copies to or from buffers, mapped reads) is not converted. Only textures that are rendered to and then sampled are covered. -- Unordered-access writes to a stand-in are not exercised by a fixture. +- B5G6R5_UNORM has no alpha; its stand-in does, so the alpha of a sampled stand-in is whatever was + rendered, not 1. +- Unordered-access writes to a stand-in and array or cube stand-ins through the wrapper are not + exercised by a fixture; the selection rule and the view verdicts for them are checked without a device. Checks: - `ctest --preset release --no-tests=error -R '^startup_packed_target$' -V`: the selection rule - against adapters described by their support bits, and the view verdicts, without a device. + against adapters described by their support bits (B5G6R5_UNORM, arrays of 2, 6, 16 and 2048 + slices, and the refused 0, 2049, multisampled and 3D cases), and the view verdicts, without a + device. The four `startup_packed_target_*_control` runs perturb the helper's answer (wrong + stand-in format, arrays left alone, B5G6R5_UNORM left alone, view kept packed) and must fail. - `ctest --preset release --no-tests=error -R '^startup_packed_target_draw_' -V`: through the wrapper, a texture of each packed format is created (slot 133), cleared through a render-target view, sampled in a draw and read back. The expected pixel follows the format this adapter - gets, so the check holds with and without the stand-in. B5G6R5_UNORM and R8G8B8A8_UNORM are - drawn as controls and never substituted; a packed view of a plain R8G8B8A8_UNORM texture and a + gets, so the check holds with and without the stand-in. R8G8B8A8_UNORM is drawn as a control + and never substituted; a packed view of a plain R8G8B8A8_UNORM texture and a B5G5R5A1 view of a B4G4R4A4 target must be refused. ## Descriptor heap starts that are not addresses diff --git a/src/startup_stubs/packed_target_format.h b/src/startup_stubs/packed_target_format.h index 5eb59f14f..ff52d8b4f 100644 --- a/src/startup_stubs/packed_target_format.h +++ b/src/startup_stubs/packed_target_format.h @@ -2,13 +2,15 @@ // the adapter cannot use the way the description asks. // // A console executable creates B5G5R5A1_UNORM and B4G4R4A4_UNORM 2D textures as render targets, -// the first also with unordered access. An adapter may not support that (measured: neither format +// the first also with unordered access. B5G6R5_UNORM and 2D arrays (a cube map is an array of six +// slices) follow the same rule. An adapter may not support that (measured: neither format // as a render target or typed UAV on an NVIDIA adapter through vkd3d-proton); the description is // then refused, the allocation-info answer is all ones and the executable gets no texture. Such a // texture is created as R8G8B8A8_UNORM and tagged with the format it stands in for; a view that // names that format on that texture is created as R8G8B8A8_UNORM. // -// Limits. The stand-in keeps 8 bits a channel where the packed format keeps 5, 4 or 1: values the +// Limits. The stand-in keeps 8 bits a channel where the packed format keeps 5, 6, 4 or 1; a +// B5G6R5_UNORM stand-in also has an alpha channel the packed format lacks (it samples as 1): values the // executable renders are not quantized, so a read of the target can differ from the console's in // the low bits (0.45 reads 115 here, 119 from B4G4R4A4). Texel data the executable writes or reads // itself in the 16-bit layout (uploads, copies to or from buffers) is not converted; only textures @@ -20,18 +22,24 @@ namespace x2w_startup { inline bool packed_target_format(DXGI_FORMAT format) { - return format == DXGI_FORMAT_B5G5R5A1_UNORM || format == DXGI_FORMAT_B4G4R4A4_UNORM; + return format == DXGI_FORMAT_B5G5R5A1_UNORM || format == DXGI_FORMAT_B4G4R4A4_UNORM || format == DXGI_FORMAT_B5G6R5_UNORM; } // The format to create a texture with. support1(format) returns the adapter's // D3D12_FORMAT_SUPPORT1 bits for a format, or 0 when the query fails. The format changes only for -// the roles that were measured: a single-sample 2D texture with one array slice that is a render +// the roles that were measured: a single-sample 2D texture or 2D array that is a render // target, alone or with unordered access, in a packed format for which the adapter lacks one of // those uses while R8G8B8A8_UNORM has them all. Anything else keeps its format. +// +// An array of 2 to D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION slices is covered the same way: the +// stand-in changes the format and nothing else, so slice count, mip count and view dimensions of +// the description and of its views are kept. Zero slices, more than the limit, three dimensions and +// multisampling are not modelled and keep their format. template DXGI_FORMAT packed_target_stand_in(const D3D12_RESOURCE_DESC& desc, Support1&& support1) { - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.DepthOrArraySize != 1 || desc.SampleDesc.Count != 1 || + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.DepthOrArraySize == 0 || + desc.DepthOrArraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION || desc.SampleDesc.Count != 1 || !packed_target_format(desc.Format) || !(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) return desc.Format; diff --git a/tests/startup_packed_target_check.cpp b/tests/startup_packed_target_check.cpp index 5282ba46f..9408a18fe 100644 --- a/tests/startup_packed_target_check.cpp +++ b/tests/startup_packed_target_check.cpp @@ -1,22 +1,45 @@ // Checks src/startup_stubs/packed_target_format.h without a device, against adapters described // by their format-support bits. +// --mutate stand-in | array | b565 | view: the helper's answer perturbed the way a wrong helper +// would answer (a stand-in in another format, arrays left alone as before, B5G6R5_UNORM left alone +// as before, the view format of the stand-in kept packed); each must fail on the rows it concerns. #include "startup_stubs/packed_target_format.h" #include +#include +#include namespace { -int failures; +int failures, checks; +const char* mutation = ""; constexpr UINT rt = D3D12_FORMAT_SUPPORT1_RENDER_TARGET, uav = D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; struct Adapter { - UINT b5g5r5a1, b4g4r4a4, rgba8; + UINT b5g5r5a1, b4g4r4a4, rgba8, b5g6r5; UINT operator()(DXGI_FORMAT format) const { return format == DXGI_FORMAT_B5G5R5A1_UNORM ? b5g5r5a1 : format == DXGI_FORMAT_B4G4R4A4_UNORM ? b4g4r4a4 - : format == DXGI_FORMAT_R8G8B8A8_UNORM ? rgba8 : rt | uav; + : format == DXGI_FORMAT_B5G6R5_UNORM ? b5g6r5 : format == DXGI_FORMAT_R8G8B8A8_UNORM ? rgba8 : rt | uav; } }; +// The helper under test, with the wrong answers a --mutate run substitutes. +DXGI_FORMAT stand_in(const D3D12_RESOURCE_DESC& desc, const Adapter& adapter) +{ + const DXGI_FORMAT got = x2w_startup::packed_target_stand_in(desc, adapter); + if (!std::strcmp(mutation, "stand-in") && got == DXGI_FORMAT_R8G8B8A8_UNORM) return DXGI_FORMAT_B8G8R8A8_UNORM; + if (!std::strcmp(mutation, "array") && desc.DepthOrArraySize != 1) return desc.Format; + if (!std::strcmp(mutation, "b565") && desc.Format == DXGI_FORMAT_B5G6R5_UNORM) return desc.Format; + return got; +} + +x2w_startup::PackedView packed_view(DXGI_FORMAT view_format, DXGI_FORMAT resource_format, DXGI_FORMAT stands_in_for) +{ + const auto got = x2w_startup::packed_view(view_format, resource_format, stands_in_for); + if (!std::strcmp(mutation, "view") && got == x2w_startup::PackedView::stand_in) return x2w_startup::PackedView::unchanged; + return got; +} + D3D12_RESOURCE_DESC texture(DXGI_FORMAT format, UINT flags, D3D12_RESOURCE_DIMENSION dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D) { D3D12_RESOURCE_DESC desc{}; @@ -33,6 +56,7 @@ D3D12_RESOURCE_DESC texture(DXGI_FORMAT format, UINT flags, D3D12_RESOURCE_DIMEN void expect(const char* name, DXGI_FORMAT got, DXGI_FORMAT wanted) { + ++checks; if (got != wanted) { std::printf("FAIL %s: format %d, expected %d\n", name, got, wanted); ++failures; @@ -41,6 +65,7 @@ void expect(const char* name, DXGI_FORMAT got, DXGI_FORMAT wanted) void view(const char* name, x2w_startup::PackedView got, x2w_startup::PackedView wanted) { + ++checks; if (got != wanted) { std::printf("FAIL %s: verdict %d, expected %d\n", name, static_cast(got), static_cast(wanted)); ++failures; @@ -48,16 +73,21 @@ void view(const char* name, x2w_startup::PackedView got, x2w_startup::PackedView } } // namespace -int main() +int main(int argc, char** argv) { - using x2w_startup::packed_target_stand_in; - using x2w_startup::packed_view; + if (argc == 3 && !std::strcmp(argv[1], "--mutate")) mutation = argv[2]; + else if (argc != 1) { + std::printf("usage: startup_packed_target_check [--mutate stand-in|array|b565|view]\n"); + return 2; + } + const auto packed_target_stand_in = stand_in; constexpr UINT RT = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, UA = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; constexpr DXGI_FORMAT b5 = DXGI_FORMAT_B5G5R5A1_UNORM, b4 = DXGI_FORMAT_B4G4R4A4_UNORM, rgba = DXGI_FORMAT_R8G8B8A8_UNORM; - const Adapter full{rt | uav, rt | uav, rt | uav}; // supports the packed formats: nothing changes - const Adapter none{0, 0, rt | uav}; // the measured case - const Adapter render_only{rt, rt, rt | uav}; // packed formats render but have no typed UAV - const Adapter bare{0, 0, 0}; // no stand-in available either + constexpr DXGI_FORMAT b565 = DXGI_FORMAT_B5G6R5_UNORM; + const Adapter full{rt | uav, rt | uav, rt | uav, rt | uav}; // supports the packed formats: nothing changes + const Adapter none{0, 0, rt | uav, 0}; // the measured case + const Adapter render_only{rt, rt, rt | uav, rt}; // packed formats render but have no typed UAV + const Adapter bare{0, 0, 0, 0}; // no stand-in available either // The two descriptions the measured run was refused: render target with unordered access, and render target. expect("b5g5r5a1 RT|UAV, unsupported", packed_target_stand_in(texture(b5, RT | UA), none), rgba); @@ -70,7 +100,6 @@ int main() expect("b4g4r4a4 RT, supported", packed_target_stand_in(texture(b4, RT), full), b4); expect("b4g4r4a4 RT, render only", packed_target_stand_in(texture(b4, RT), render_only), b4); expect("b5g5r5a1 RT, no stand-in", packed_target_stand_in(texture(b5, RT), bare), b5); - expect("b5g6r5 RT", packed_target_stand_in(texture(DXGI_FORMAT_B5G6R5_UNORM, RT), none), DXGI_FORMAT_B5G6R5_UNORM); expect("rgba8 RT", packed_target_stand_in(texture(rgba, RT), none), rgba); expect("b5g5r5a1 sampled only", packed_target_stand_in(texture(b5, 0), none), b5); expect("b5g5r5a1 UAV without RT", packed_target_stand_in(texture(b5, UA), none), b5); @@ -78,11 +107,58 @@ int main() expect("b4g4r4a4 1D RT", packed_target_stand_in(texture(b4, RT, D3D12_RESOURCE_DIMENSION_TEXTURE1D), none), b4); expect("buffer", packed_target_stand_in(texture(b5, UA, D3D12_RESOURCE_DIMENSION_BUFFER), none), b5); D3D12_RESOURCE_DESC shaped = texture(b5, RT); - shaped.DepthOrArraySize = 6; - expect("b5g5r5a1 RT array", packed_target_stand_in(shaped, none), b5); - shaped = texture(b5, RT); shaped.SampleDesc.Count = 4; expect("b5g5r5a1 RT multisampled", packed_target_stand_in(shaped, none), b5); + shaped = texture(b565, RT); + shaped.SampleDesc.Count = 2; + expect("b5g6r5 RT multisampled", packed_target_stand_in(shaped, none), b565); + + // B5G6R5_UNORM follows the same rule as the other two packed formats. + expect("b5g6r5 RT, unsupported", packed_target_stand_in(texture(b565, RT), none), rgba); + expect("b5g6r5 RT|UAV, render only", packed_target_stand_in(texture(b565, RT | UA), render_only), rgba); + expect("b5g6r5 RT, supported", packed_target_stand_in(texture(b565, RT), full), b565); + expect("b5g6r5 RT|UAV, supported", packed_target_stand_in(texture(b565, RT | UA), full), b565); + expect("b5g6r5 RT, no stand-in", packed_target_stand_in(texture(b565, RT), bare), b565); + expect("b5g6r5 sampled only", packed_target_stand_in(texture(b565, 0), none), b565); + expect("b5g6r5 3D RT", packed_target_stand_in(texture(b565, RT, D3D12_RESOURCE_DIMENSION_TEXTURE3D), none), b565); + expect("b5g6r5 depth-stencil", packed_target_stand_in(texture(b565, RT | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), none), b565); + + // Arrays and cube maps (six slices): the format follows the same rule for 2 to 2048 slices; 0 and + // more than the limit keep the format. The slice count is not part of the answer. + for (const UINT slices : {2u, 6u, 16u, 2048u}) { + shaped = texture(b5, RT); + shaped.DepthOrArraySize = static_cast(slices); + char name[64]; + std::snprintf(name, sizeof(name), "b5g5r5a1 RT array of %u, unsupported", slices); + expect(name, packed_target_stand_in(shaped, none), rgba); + std::snprintf(name, sizeof(name), "b5g5r5a1 RT array of %u, supported", slices); + expect(name, packed_target_stand_in(shaped, full), b5); + shaped.Format = b565; + std::snprintf(name, sizeof(name), "b5g6r5 RT array of %u, unsupported", slices); + expect(name, packed_target_stand_in(shaped, none), rgba); + shaped.Format = b4; + std::snprintf(name, sizeof(name), "b4g4r4a4 RT array of %u, render only", slices); + expect(name, packed_target_stand_in(shaped, render_only), b4); + } + for (const UINT slices : {0u, 2049u, 65535u}) { + shaped = texture(b565, RT); + shaped.DepthOrArraySize = static_cast(slices); + char name[64]; + std::snprintf(name, sizeof(name), "b5g6r5 RT with %u slices", slices); + expect(name, packed_target_stand_in(shaped, none), b565); + } + shaped = texture(b5, RT | UA); + shaped.DepthOrArraySize = 6; + shaped.MipLevels = 3; + expect("b5g5r5a1 RT|UAV cube with mips", packed_target_stand_in(shaped, none), rgba); + shaped.SampleDesc.Count = 4; + expect("b5g5r5a1 RT|UAV cube multisampled", packed_target_stand_in(shaped, none), b5); + shaped = texture(b5, RT, D3D12_RESOURCE_DIMENSION_TEXTURE3D); + shaped.DepthOrArraySize = 6; + expect("b5g5r5a1 3D with depth 6", packed_target_stand_in(shaped, none), b5); + shaped = texture(rgba, RT); + shaped.DepthOrArraySize = 6; + expect("rgba8 RT array", packed_target_stand_in(shaped, none), rgba); // Views: a packed view becomes RGBA8 only on the stand-in for that very format. using x2w_startup::PackedView; @@ -96,11 +172,17 @@ int main() view("b5g5r5a1 view of the b4g4r4a4 stand-in", packed_view(b5, rgba, b4), PackedView::refused); view("b5g5r5a1 view of a b4g4r4a4 texture", packed_view(b5, b4, plain), PackedView::refused); view("b5g5r5a1 view of a bgra8 texture", packed_view(b5, DXGI_FORMAT_B8G8R8A8_UNORM, plain), PackedView::refused); + view("b5g6r5 view of its stand-in", packed_view(b565, rgba, b565), PackedView::stand_in); + view("b5g6r5 view of a b5g6r5 texture", packed_view(b565, b565, plain), PackedView::unchanged); + view("b5g6r5 view of a plain rgba8 texture", packed_view(b565, rgba, plain), PackedView::refused); + view("b5g6r5 view of the b5g5r5a1 stand-in", packed_view(b565, rgba, b5), PackedView::refused); + view("b5g5r5a1 view of the b5g6r5 stand-in", packed_view(b5, rgba, b565), PackedView::refused); + view("b5g6r5 view of a b5g5r5a1 texture", packed_view(b565, b5, plain), PackedView::refused); if (failures) { std::printf("startup_packed_target: %d FAILED\n", failures); return 1; } - std::printf("startup_packed_target: PASS (3 stand-ins, 13 unchanged, 9 view verdicts)\n"); + std::printf("startup_packed_target: PASS (%d rows)\n", checks); return 0; } diff --git a/tests/startup_packed_target_draw_check.py b/tests/startup_packed_target_draw_check.py index f99a48db5..168fef89d 100644 --- a/tests/startup_packed_target_draw_check.py +++ b/tests/startup_packed_target_draw_check.py @@ -13,9 +13,8 @@ B4G4R4A4_UNORM (119, 51, 204, 255) B5G6R5_UNORM (115, 53, 206, 255) -Controls: B5G6R5_UNORM (a packed format outside the rule, never substituted) and R8G8B8A8_UNORM with -its own view format must draw their own values. A packed view of a plain R8G8B8A8_UNORM texture, and -a B5G5R5A1 view of a B4G4R4A4 texture, must be refused by name and leave the draw without the clear +Control: R8G8B8A8_UNORM with its own view format must draw its own values. A packed view of a plain +R8G8B8A8_UNORM texture, and a B5G5R5A1 view of a B4G4R4A4 texture, must be refused by name and leave the draw without the clear colour. Not covered: unordered-access writes, and texel data written or read by the CPU in the 16-bit layout. @@ -117,18 +116,18 @@ def refused(name, resource_format, flags, view_format): paths = set() for name, resource_format, flags in (("B5G5R5A1 render target with unordered access", B5G5R5A1, RT | UAV), - ("B4G4R4A4 render target", B4G4R4A4, RT)): + ("B4G4R4A4 render target", B4G4R4A4, RT), + ("B5G6R5 render target", B5G6R5, RT)): created, got = rendered(name, resource_format, flags, {resource_format, RGBA8}) paths.add("stand-in" if created == RGBA8 else "as described") - # Controls that draw: never substituted. - control, _ = rendered("control, B5G6R5 render target", B5G6R5, RT, {B5G6R5}) + # Control that draws: never substituted. plain, _ = rendered("control, R8G8B8A8 render target", RGBA8, RT, {RGBA8}) assert stored(B5G5R5A1) != stored(RGBA8) != stored(B4G4R4A4) and stored(B5G6R5) != stored(RGBA8) # Controls that must be refused. refused("B5G5R5A1 views of a plain R8G8B8A8 texture", RGBA8, RT, B5G5R5A1) refused("B5G5R5A1 views of a B4G4R4A4 render target", B4G4R4A4, RT, B5G5R5A1) print(f"startup_packed_target_draw: PASS on {backend} (packed targets drawn {' and '.join(sorted(paths))} on this adapter; " - f"2 drawn controls, 2 refused view pairs; unordered-access writes and CPU-written texels not covered)") + f"1 drawn control, 2 refused view pairs; unordered-access writes and CPU-written texels not covered)") return 0 From f6399bda54995a449d1d25e420d17348d196f547 Mon Sep 17 00:00:00 2001 From: SuperCraft3M Date: Tue, 24 Nov 2026 12:53:29 +0100 Subject: [PATCH 069/775] docs: record RTX 4070 BVH retest --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b4f7eb62b..f5e0931b0 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | Radeon RX 570 Series | 64 | Skipped, Shader Model 6.5 | Skipped, DXR unsupported | [31.0.21029.6002 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064985486) | | AMD Radeon RX 6900 XT | 32 | Passed, 64 lanes | 408 queries passed | [32.0.21043.19003 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064998365) | | NVIDIA GeForce GTX 1660 Ti | 32 | Skipped, lane range 32–32 | Skipped, DXR tier 1.0 | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065028400) | -| NVIDIA GeForce RTX 4070 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1714 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065102476) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065617429) · [Independent 32.0.16.2124 run, source build at b7f7e3f](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065336644) | +| NVIDIA GeForce RTX 4070 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1714 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065102476) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065617429) · [Independent 32.0.16.2124 run, source build at b7f7e3f](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065336644) · [32.0.16.2114 retest, Windows 11 build 26300.9711](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7130486482) | | NVIDIA GeForce RTX 2080 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065666797) · [32.0.16.2124 report, device 1e82, full source-built suite at 14e5456](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7076848822) | | NVIDIA GeForce RTX 4080 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065823692) | | NVIDIA GeForce RTX 5090 | 32 | Skipped, lane range 32–32 | 408 queries passed per run | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065874287) · [Full source-built hardware suite at ee39536](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065978183) · [Independent run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068398676) · [32.0.16.2114 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7086369360) | From f998aad12b913e5c4fc2210ff4bc765963d03445 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:53:51 +0800 Subject: [PATCH 070/775] docs: record the exact-mip MinLod target on a physical Intel adapter The exact-mip paragraph states a WARP claim only and asks for physical-adapter claims with adapter, driver, Windows build, DXC version, debug-layer status and runtime. Add that record for the Intel Arc 140T at bb6c9a0c: clamp 1 read mip 1 for translated SPIR-V and the direct HLSL control, the stale mip-2 reference reported its mismatch at pixel (0, 0), and the integer-clamp cases of spirv_minlod_levels_* read mips 0 to 3 at clamps 0 to 3, with zero D3D12 debug errors and warnings. Docs only. --- docs/experiments.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index db9ac15ef..cb201ebba 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8432,6 +8432,13 @@ only. Physical-adapter claims remain separate and require the adapter, driver, Windows build, DXC version and flags, debug-layer status, and runtime reported explicitly. +On Windows 11 build 26300.9974, the Intel Arc 140T (8086:7d51), driver +32.0.101.8132, DXC 1.8.2502.11, debug layer enabled, passed the same target for +translated SPIR-V and the direct HLSL control: clamp 1 read mip 1 and the stale +mip-2 reference reported its mismatch at pixel (0, 0). The integer-clamp cases of +`spirv_minlod_levels_*` read mips 0, 1, 2 and 3 at clamps 0 to 3 on the same +adapter, with zero D3D12 debug errors and warnings. + `spirv_minlod_levels_*` compiles at `ps_6_0`: - With point mip filtering, each integer clamp from 0 through 3 selects its From 4ec5dae113bdb0ad9efecc29011396973ba3bece Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:54:33 +0100 Subject: [PATCH 071/775] tests: fix DXGI_FORMAT_R32_TYPELESS enum value (39) in buffer SRV check --- tests/startup_address_buffer_srv_check.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index 094b2b183..52745d4b9 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -15,7 +15,7 @@ def check_refusal_lines(log): prefix + r"unavailable buffer at the supplied address: reason=buffer_unavailable " + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " - + r"view\{dim=1 fmt=62 map=0x1688 first=0 count=4 stride=0 flags=0x1 \(buffer views are not supported\)\} " + + r"view\{dim=1 fmt=39 map=0x1688 first=0 count=4 stride=0 flags=0x1 \(buffer views are not supported\)\} " + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", ] lines = [line.rstrip() for line in log.splitlines() if "Device::slot70" in line] From 0968f732b68f65b34054ab4135547f456d180a72 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:55:03 +0800 Subject: [PATCH 072/775] docs: record the compute-store readback on Intel Xe2 --- docs/experiments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index db9ac15ef..3fe288ad8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2996,7 +2996,7 @@ python3 -B tools/compute_store_aot.py local.dxbc --llvm libLLVM-15.so.1 --table- python3 -B tests/compute_store_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 ``` -Build the emitted source with `dxc -T cs_6_0 -E main`. The Windows fixture reads back all 320 words, including gaps between records and the untouched tail, after one and three indexed groups. A wrong stored word and a wrong guard word must both fail. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_'`. +Build the emitted source with `dxc -T cs_6_0 -E main`. The Windows fixture reads back all 320 words, including gaps between records and the untouched tail, after one and three indexed groups. A wrong stored word and a wrong guard word must both fail. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_'`. On Windows 11 build 26300.9974, the Intel Arc 140T (32.0.101.8132) matched all 320 words after one and after three indexed groups, with zero D3D12 debug errors and warnings. ### gfx1030 MUBUF cache-invalidation rejection From c44bd0ad785cc4a01110bd05360710fdf3a498f0 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:58:10 +0100 Subject: [PATCH 073/775] tools/startup: add redacted 1-run telemetry summarizer (triage_run.py) --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 2 + docs/startup-runtime.md | 6 + tests/startup_triage_run_check.py | 160 ++++++++++ tools/startup/triage_run.py | 497 ++++++++++++++++++++++++++++++ 5 files changed, 666 insertions(+) create mode 100644 tests/startup_triage_run_check.py create mode 100644 tools/startup/triage_run.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b73d82490..8f84ae896 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -112,6 +112,7 @@ jobs: python -B tests/startup_image_2d_array_check.py python -B tests/startup_host_cpu_check.py python -B tests/startup_translator_check.py + python -B tests/startup_triage_run_check.py python -B tests/startup_flat_param_check.py python -B tests/startup_inline_sampler_check.py build-and-test: diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f61af885..5b9af7cf9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1490,6 +1490,8 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: descriptor offsets inside wide scalar loads (no game data). add_test(NAME startup_translator COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_translator_check.py") + add_test(NAME startup_triage_run COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_triage_run_check.py") add_test(NAME xmem_shim_mapped_pages COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xmem_mapped_pages_check.py" "$") # Large batches: pages as slots of shared sections, adjacent pages in one view. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9ff8d97c1..0b2d65a46 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -172,6 +172,12 @@ socket, NetBIOS and DNS devices are refused (`--offline 0` turns this off; do no `tools/startup/live_view.py` follows a run in a second console. `X2W_TRAP_DUMP="exe+RVA:len,reg+off:len"` adds memory dumps to the stop report. +`tools/startup/triage_run.py` summarizes a log directory (and optional `--shader-cache `) +into a path-redacted, address-redacted Markdown report (`Device::slot70` refusals, unhandled +`x2w-d3d12` / trap slots, `x2w-dstorage` failures and status HRESULTs, `x2w-runtime` failing calls, +and `.fail` shader reasons). Check with `python3 -B tests/startup_triage_run_check.py` (ctest +`startup_triage_run`). + ## Launcher check `tests/startup_launch_check.py` (ctest `startup_launch`) drives `tools/startup/launch.py` on the diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py new file mode 100644 index 000000000..49ef7f8ad --- /dev/null +++ b/tests/startup_triage_run_check.py @@ -0,0 +1,160 @@ +"""Tests for tools/startup/triage_run.py using synthetic logs and negative controls.""" + +from __future__ import annotations + +from pathlib import Path +import subprocess +import sys +import tempfile + + +REPO_ROOT = Path(__file__).resolve().parent.parent +TOOLS_STARTUP = REPO_ROOT / "tools" / "startup" +sys.path.insert(0, str(TOOLS_STARTUP)) +import triage_run # noqa: E402 + + +SYNTHETIC_STDERR = """\ +x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description res{dim=1 fmt=0 size=4096x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0} view{dim=11 fmt=0 map=0x1688 raw=55667788,11223344,00000000,00000000,00000000,00000000 (acceleration structure views are not supported)} dest=0x00007ff712340000 dest_in_view_heap=1 address=0x00000180deadbeef address_readable=0 +x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description res{dim=1 fmt=0 size=8192x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0} view{dim=11 fmt=0 map=0x1688 raw=55667788,11223344,00000000,00000000,00000000,00000000 (acceleration structure views are not supported)} dest=0x00007ff712340080 dest_in_view_heap=1 address=0x00000180cafebabe address_readable=1 +x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=destination_outside_view_heaps res{dim=3 fmt=98 size=128x128x2 mips=6 layout=0x105 flags=0x300000 align=65536 samples=1/0} view{dim=5 fmt=98 map=0x1688 mostmip=1 mips=5 first=1 count=1 plane=0 clamp=0.5} dest=0x00007ff712341001 dest_in_view_heap=0 address=0x0000018000007000 address_readable=1 +x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unreadable_resource res{unreadable} view{unreadable} dest=0x1000 dest_in_view_heap=1 address=0x0 address_readable=0 +x2w-noop d3d12_xs!Device::slot44 rcx=0x0000018011112222 rdx=0x0000018033334444 r8=0x0 r9=0x0 ret=sample_app.exe+0x1234 exit=0xe257002c +x2w-trap d3d12_xs!Device::slot99 rcx=0x0000018011112222 rdx=0x0 r8=0x0 r9=0x0 ret=C:\\Users\\alice\\secret\\game.exe+0x4560 exit=0xe2570063 +x2w-d3d12 Device::slot10(CreateGraphicsPipelineState) desc=[00 01] riid={1234} -> trap +x2w-d3d12-debug [Device 44] sev=2 id=999 Failed reading C:\\Users\\alice\\secret\\game.exe at 0x00007ff7deadbeef +x2w-dstorage options=0x1 dest=0x0000018044440000 dest_size=0x1000 source=0x1 offset=0x0 size=0x100 -> zlib failed +x2w-dstorage options=0x1 dest=0x0000018044441000 dest_size=0x1000 source=0x1 offset=0x200 size=0x100 -> zlib failed +x2w-dstorage options=0x1 dest=0x0000018044442000 dest_size=0x1000 source=0x1 offset=0x400 size=0x100 -> done +x2w-dstorage Factory::OpenFile path="C:\\Users\\alice\\secret\\data.pak" riid={abcd} -> fail (err 2) +x2w-dstorage StatusArray::GetHResult index=0 -> 0x80004005 +x2w-dstorage StatusArray::GetHResult index=1 -> 0x00000000 +x2w-runtime 12345678::slot5(0x1, 0x2, 0x3 | 0x4, 0x5) -> 0xffffffff80004005 from +0x100 +x2w-runtime 12345678::slot5(0x1, 0x2, 0x3 | 0x4, 0x5) -> 0x80004005 from +0x104 +x2w-runtime 12345678::slot6(0x1, 0x2, 0x3 | 0x4, 0x5) -> 0x0 from +0x108 +x2w-runtime persistent local storage: local object instead of 0x80070005 +""" + + +def check_aggregation_and_redaction(failures: list[str]) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + (logdir / "stderr.txt").write_text(SYNTHETIC_STDERR, encoding="utf-8") + + cache_dir = root / "shader_cache" + cache_dir.mkdir() + (cache_dir / "0000000000000001.fail").write_text( + "image_load_mip tfe\n", encoding="utf-8" + ) + (cache_dir / "0000000000000002.fail").write_text( + "image_load_mip tfe\n", encoding="utf-8" + ) + (cache_dir / "0000000000000003.fail").write_text( + "fxc ps: /home/alice/secret/shader.hlsl(1,1): error X3000 at 0x00007ff712345678\n", + encoding="utf-8", + ) + + report = triage_run.triage_run(logdir, shader_cache=cache_dir, max_items=16) + + expected_snippets = [ + "Log files scanned: `1`", + "| 2 | unsupported_description | 1 | 0 | 11 | 0 | 0x1 | 0x0 |", + "| 1 | destination_outside_view_heaps | 3 | 98 | 5 | 98 | 0x105 | 0x300000 |", + "| 1 | unreadable_resource | unreadable | unreadable | unreadable | unreadable | unreadable | unreadable |", + "| 1 | `x2w-noop d3d12_xs!Device::slot44` |", + "| 1 | `Device::slot10(CreateGraphicsPipelineState)` |", + "| 2 | zlib failed |", + "| 1 | OpenFile: fail (err 2) |", + "| 1 | `0x80004005` |", + "| 2 | `12345678::slot5` | `0x80004005` |", + "| 1 | `persistent_local_storage` | `0x80070005` |", + "| 2 | `image_load_mip tfe` |", + ] + for snippet in expected_snippets: + if snippet not in report: + failures.append(f"missing expected summary line: {snippet!r}") + + # Negative controls: sensitive paths, executables, and 64-bit addresses must never leak. + forbidden = [ + "alice", + "game.exe", + "sample_app.exe", + "C:\\Users", + "/home/alice", + "0x00007ff712340000", + "0x00000180deadbeef", + "0x00007ff7deadbeef", + "0x00007ff712345678", + "data.pak", + ] + for secret in forbidden: + if secret in report: + failures.append(f"negative control failed: leaked {secret!r} in report") + + +def check_redaction_helper(failures: list[str]) -> None: + cases = [ + (r'C:\Users\alice\secret\game.exe', ""), + (r'"C:\Program Files\My App\title.exe"', '""'), + ("/home/alice/dumps/run1/stderr.txt", ""), + ("/Users/alice/Desktop/tool.exe", ""), + ("ret=sample_app.exe+0x1234", "ret=+0x1234"), + ("ptr=0x00007ff712345678 hr=0x80004005", "ptr=0x hr=0x80004005"), + ] + for raw, want in cases: + got = triage_run.redact(raw) + if got != want: + failures.append(f"redact({raw!r}) = {got!r}, expected {want!r}") + + +def check_empty_and_missing_dirs(failures: list[str]) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + empty_dir = root / "empty" + empty_dir.mkdir() + missing_dir = root / "does_not_exist" + + for target in (empty_dir, missing_dir): + report = triage_run.triage_run(target, shader_cache=missing_dir) + if "Log files scanned: `0`" not in report: + failures.append(f"expected 0 scanned files for {target}") + if "_None observed._" not in report: + failures.append(f"expected '_None observed._' for {target}") + + +def check_cli_invocation(failures: list[str]) -> None: + with tempfile.TemporaryDirectory() as tmp: + log_file = Path(tmp) / "single.log" + log_file.write_text( + "x2w-dstorage options=0x1 dest=0x0000018000001000 dest_size=0x10 " + "source=0x1 offset=0x0 size=0x10 -> read failed\n", + encoding="utf-8", + ) + proc = subprocess.run( + [sys.executable, "-B", str(TOOLS_STARTUP / "triage_run.py"), str(log_file), "--max-items", "4"], + capture_output=True, + text=True, + check=False, + ) + if proc.returncode != 0: + failures.append(f"CLI exited with {proc.returncode}: {proc.stderr}") + elif "| 1 | read failed |" not in proc.stdout: + failures.append(f"CLI output missing expected row: {proc.stdout!r}") + + +def main() -> int: + failures: list[str] = [] + check_aggregation_and_redaction(failures) + check_redaction_helper(failures) + check_empty_and_missing_dirs(failures) + check_cli_invocation(failures) + for item in failures: + print("FAIL", item) + print(f"startup triage_run checks: {len(failures)} failed") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py new file mode 100644 index 000000000..c98344f4a --- /dev/null +++ b/tools/startup/triage_run.py @@ -0,0 +1,497 @@ +#!/usr/bin/env python3 +"""Summarize a startup log directory (and optional shader cache) into redacted Markdown. + +Reads raw logs produced by tools/startup/run.ps1 / debug_launch.py and emits a +title-neutral, path-redacted, address-redacted Markdown summary suitable for a +GitHub issue. Uses only the Python 3 standard library. +""" + +from __future__ import annotations + +import argparse +from collections import Counter +from pathlib import Path +import re +import sys +from typing import Iterable + + +LOG_EXTENSIONS = {".txt", ".log", ".out"} + +DSTORAGE_OK_OUTCOMES = { + "done", + "empty", + "inflated", + "inflated (larger/short)", + "inflated (chunked stream piece 0)", + "inflated (slice from stream cache)", + "bcpack decoded", + "inflated + bcpack decoded", +} + +# Redaction patterns (applied in order from most specific/broadest path to tokens). +RE_QUOTED_WIN_PATH = re.compile(r'"([A-Za-z]:\\[^"\r\n]+|[A-Za-z]:/[^"\r\n]+|\\\\[^\\"\r\n]+\\[^"\r\n]+)"') +RE_WIN_PATH = re.compile(r'(?:[A-Za-z]:\\[^\s"\'<>|]+|[A-Za-z]:/[^\s"\'<>|]+|\\\\[^\s"\'<>|\\]+\\[^\s"\'<>|]+)') +RE_QUOTED_POSIX_PATH = re.compile( + r'"(/(?:home|Users|mnt|tmp|var|opt|root|srv|private|Volumes)/[^"\r\n]+)"' +) +RE_POSIX_PATH = re.compile( + r'/(?:home|Users|mnt|tmp|var|opt|root|srv|private|Volumes)(?:/[^\s"\'<>|]+)+' +) +RE_EXE_NAME = re.compile(r'\b[A-Za-z0-9_.\-]+\.exe\b', re.IGNORECASE) +RE_ADDR64 = re.compile(r'\b0x[0-9a-fA-F]{9,}\b') + +# Log line patterns matching src/startup_stubs/*. +RE_SLOT70 = re.compile( + r'x2w-d3d12\s+Device::slot70\b.*?\breason=(\S+)\s+res\{([^}]*)\}\s+view\{([^}]*)\}' +) +RE_KV = re.compile(r'(\w+)=([^\s}]+)') + +RE_TRAP_TAG = re.compile(r'^(x2w-(?:trap|noop|continue|fail))\s+(\S+)') +RE_D3D12_PIPELINE_TRAP = re.compile( + r'x2w-d3d12\s+Device::slot(\d+)\((Create(?:Graphics|Compute)PipelineState)\)' +) +RE_D3D12_IID_PASS = re.compile(r'x2w-d3d12\s+Device::slot(\d+)\s+passes an IID:') +RE_D3D12_VIEW_SKIPPED = re.compile(r'x2w-d3d12\s+Device::slot(\d+)\s+view skipped:\s+(.+)$') +RE_D3D12_SLOT_CALL = re.compile(r'x2w-d3d12\s+([A-Za-z0-9_]+::slot\d+)\b') +RE_D3D12_REMOVED = re.compile( + r'x2w-d3d12\s+DEVICE REMOVED,\s+reason\s+(0x[0-9a-fA-F]+),\s+first noticed after\s+(.+)$' +) +RE_D3D12_DEBUG = re.compile(r'x2w-d3d12-debug\s+\[([^\]]+)\]\s+sev=(\d+)\s+id=(\d+)\s+(.+)$') + +RE_DSTORAGE_OUTCOME = re.compile(r'x2w-dstorage\s+options=0x[0-9a-fA-F]+.*?->\s+(.+)$') +RE_DSTORAGE_ENTRY_FAIL = re.compile( + r'x2w-dstorage\s+entry type\s+\d+\s+failed:\s+(.+?)(?:\s+\(options=0x[0-9a-fA-F]+\))?$' +) +RE_DSTORAGE_ZLIB_FAIL = re.compile(r'x2w-dstorage\s+zlib failure:\s+(.+)$') +RE_DSTORAGE_OPENFILE_FAIL = re.compile(r'x2w-dstorage\s+Factory::OpenFile\s+.*?->\s+(fail\b.*)$') +RE_DSTORAGE_HRESULT = re.compile( + r'x2w-dstorage\s+StatusArray::GetHResult\s+index=\d+\s+->\s+(0x[0-9a-fA-F]+)' +) +RE_DSTORAGE_SIGNAL = re.compile( + r'x2w-dstorage\s+Queue::EnqueueSignal\s+.*?->\s+(0x[0-9a-fA-F]+)' +) + +RE_RUNTIME_CALL = re.compile( + r'x2w-(?:runtime|api)\s+([0-9a-fA-F]+::slot\d+)(?:\([^)]*\))?\s+->\s+(0x[0-9a-fA-F]+)' +) +RE_RUNTIME_STORAGE = re.compile( + r'x2w-runtime\s+persistent local storage:\s+local object instead of\s+(0x[0-9a-fA-F]+)' +) +RE_RUNTIME_GAMESAVE = re.compile( + r'x2w-runtime\s+game save:\s+update refused\s+\(status\s+(-?\d+)\)' +) + + +def redact(text: str) -> str: + """Strip local paths, executable names, and 64-bit addresses from a log snippet.""" + out = RE_QUOTED_WIN_PATH.sub('""', text) + out = RE_WIN_PATH.sub("", out) + out = RE_QUOTED_POSIX_PATH.sub('""', out) + out = RE_POSIX_PATH.sub("", out) + out = RE_EXE_NAME.sub("", out) + out = RE_ADDR64.sub("0x", out) + return out + + +def _md_cell(value: object) -> str: + return str(value).replace("|", "\\|").replace("\r", " ").replace("\n", " ") + + +def _parse_kv_block(block: str) -> dict[str, str]: + if block.strip() == "unreadable": + return {"_unreadable": "1"} + return dict(RE_KV.findall(block)) + + +def _is_failed_hresult(hex_text: str) -> tuple[bool, str]: + val = int(hex_text, 16) & 0xFFFFFFFF + return (val & 0x80000000) != 0, f"0x{val:08x}" + + +def iter_log_files(log_target: Path) -> list[Path]: + """Return sorted log files under log_target (or [log_target] if it is a file).""" + if not log_target.exists(): + return [] + if log_target.is_file(): + return [log_target] + if not log_target.is_dir(): + return [] + files = [ + p + for p in log_target.rglob("*") + if p.is_file() and p.suffix.lower() in LOG_EXTENSIONS + ] + files.sort() + return files + + +def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]: + """Aggregate startup telemetry counters from an iterable of log lines.""" + slot70_refusals: Counter[tuple[str, str, str, str, str, str, str]] = Counter() + d3d12_unhandled: Counter[str] = Counter() + d3d12_debug: Counter[tuple[str, str, str, str]] = Counter() + dstorage_failures: Counter[str] = Counter() + dstorage_hresults: Counter[str] = Counter() + runtime_failures: Counter[tuple[str, str]] = Counter() + + for raw_line in lines: + line = raw_line.strip() + if not line: + continue + + # 1. slot70 memory SRV refusals + m = RE_SLOT70.search(line) + if m: + reason, res_raw, view_raw = m.group(1), m.group(2), m.group(3) + res = _parse_kv_block(res_raw) + view = _parse_kv_block(view_raw) + if "_unreadable" in res: + dim = fmt = layout = flags = "unreadable" + else: + dim = res.get("dim", "?") + fmt = res.get("fmt", "?") + layout = res.get("layout", "?") + flags = res.get("flags", "?") + if "_unreadable" in view: + view_dim = view_fmt = "unreadable" + else: + view_dim = view.get("dim", "?") + view_fmt = view.get("fmt", "?") + slot70_refusals[(reason, dim, fmt, view_dim, view_fmt, layout, flags)] += 1 + continue + + # 2. x2w-trap / x2w-noop / x2w-continue / x2w-fail + m = RE_TRAP_TAG.match(line) + if m: + tag, target = m.group(1), redact(m.group(2)) + d3d12_unhandled[f"{tag} {target}"] += 1 + continue + + # 3. x2w-d3d12-debug + m = RE_D3D12_DEBUG.search(line) + if m: + ctx, sev, msg_id, msg = m.group(1), m.group(2), m.group(3), redact(m.group(4)) + if len(msg) > 120: + msg = msg[:117] + "..." + d3d12_debug[(redact(ctx), sev, msg_id, msg)] += 1 + continue + + # 4. x2w-d3d12 unhandled/trapped/skipped slots & device removed + if "x2w-d3d12" in line: + m = RE_D3D12_REMOVED.search(line) + if m: + d3d12_unhandled[f"DEVICE REMOVED {m.group(1)} after {redact(m.group(2))}"] += 1 + continue + m = RE_D3D12_PIPELINE_TRAP.search(line) + if m: + d3d12_unhandled[f"Device::slot{m.group(1)}({m.group(2)})"] += 1 + continue + m = RE_D3D12_IID_PASS.search(line) + if m: + d3d12_unhandled[f"Device::slot{m.group(1)} (passes IID)"] += 1 + continue + m = RE_D3D12_VIEW_SKIPPED.search(line) + if m: + d3d12_unhandled[f"Device::slot{m.group(1)} view skipped: {redact(m.group(2))}"] += 1 + continue + m = RE_D3D12_SLOT_CALL.search(line) + if m: + d3d12_unhandled[m.group(1)] += 1 + continue + + # 5. x2w-dstorage failures & status HRESULTs + if "x2w-dstorage" in line: + m = RE_DSTORAGE_OUTCOME.search(line) + if m: + outcome = m.group(1).strip() + if outcome not in DSTORAGE_OK_OUTCOMES: + dstorage_failures[redact(outcome)] += 1 + continue + m = RE_DSTORAGE_ENTRY_FAIL.search(line) + if m: + dstorage_failures[f"entry failed: {redact(m.group(1))}"] += 1 + continue + m = RE_DSTORAGE_ZLIB_FAIL.search(line) + if m: + dstorage_failures["zlib failure"] += 1 + continue + m = RE_DSTORAGE_OPENFILE_FAIL.search(line) + if m: + dstorage_failures[f"OpenFile: {redact(m.group(1))}"] += 1 + continue + m = RE_DSTORAGE_HRESULT.search(line) + if m: + _, norm_hr = _is_failed_hresult(m.group(1)) + dstorage_hresults[norm_hr] += 1 + continue + m = RE_DSTORAGE_SIGNAL.search(line) + if m: + failed, norm_hr = _is_failed_hresult(m.group(1)) + if failed: + dstorage_hresults[norm_hr] += 1 + continue + + # 6. x2w-runtime / x2w-api failing methods / HRESULTs + if "x2w-runtime" in line or "x2w-api" in line: + m = RE_RUNTIME_CALL.search(line) + if m: + failed, norm_hr = _is_failed_hresult(m.group(2)) + if failed: + runtime_failures[(m.group(1), norm_hr)] += 1 + continue + m = RE_RUNTIME_STORAGE.search(line) + if m: + _, norm_hr = _is_failed_hresult(m.group(1)) + runtime_failures[("persistent_local_storage", norm_hr)] += 1 + continue + m = RE_RUNTIME_GAMESAVE.search(line) + if m: + runtime_failures[("game_save_update", f"status {m.group(1)}")] += 1 + continue + + return { + "slot70_refusals": slot70_refusals, + "d3d12_unhandled": d3d12_unhandled, + "d3d12_debug": d3d12_debug, + "dstorage_failures": dstorage_failures, + "dstorage_hresults": dstorage_hresults, + "runtime_failures": runtime_failures, + } + + +def summarize_shader_cache(cache_dir: Path | None) -> Counter[str]: + """Count .fail Unsupported(...) / fxc reasons in X2W_SHADER_CACHE.""" + reasons: Counter[str] = Counter() + if cache_dir is None or not cache_dir.is_dir(): + return reasons + for fail_path in sorted(cache_dir.glob("*.fail")): + try: + text = fail_path.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + first_line = "" + for line in text.splitlines(): + stripped = line.strip() + if stripped: + first_line = stripped + break + if not first_line: + first_line = "(empty .fail)" + cleaned = redact(first_line) + if len(cleaned) > 120: + cleaned = cleaned[:117] + "..." + reasons[cleaned] += 1 + return reasons + + +def _format_table( + headers: list[str], + rows: list[list[object]], + total_unique: int, + total_events: int, + max_items: int, +) -> list[str]: + if not rows: + return ["_None observed._", ""] + lines = [ + "| " + " | ".join(headers) + " |", + "| " + " | ".join(["---"] * len(headers)) + " |", + ] + for row in rows[:max_items]: + lines.append("| " + " | ".join(_md_cell(c) for c in row) + " |") + if total_unique > max_items: + lines.append( + f"_Showing top {max_items} of {total_unique} unique entries ({total_events} total events)._" + ) + lines.append("") + return lines + + +def format_markdown( + summary: dict[str, Counter], + shader_failures: Counter[str], + files_scanned: int, + shader_cache_provided: bool, + max_items: int, +) -> str: + """Render aggregated counters as clean-room Markdown.""" + out: list[str] = [ + "## Startup Run Triage Summary", + "", + f"- Log files scanned: `{files_scanned}`", + f"- `slot70` memory SRV refusals: `{sum(summary['slot70_refusals'].values())}` " + f"({len(summary['slot70_refusals'])} unique)", + f"- `x2w-d3d12` / trap slot events: `{sum(summary['d3d12_unhandled'].values())}` " + f"({len(summary['d3d12_unhandled'])} unique)", + f"- `x2w-d3d12-debug` messages: `{sum(summary['d3d12_debug'].values())}` " + f"({len(summary['d3d12_debug'])} unique)", + f"- `x2w-dstorage` failures: `{sum(summary['dstorage_failures'].values())}` " + f"({len(summary['dstorage_failures'])} unique)", + f"- `x2w-runtime` failing calls: `{sum(summary['runtime_failures'].values())}` " + f"({len(summary['runtime_failures'])} unique)", + ] + if shader_cache_provided: + out.append( + f"- `X2W_SHADER_CACHE` `.fail` shaders: `{sum(shader_failures.values())}` " + f"({len(shader_failures)} unique reasons)" + ) + out.append("") + + # 1. slot70 refusals + out.extend(["### `Device::slot70` Memory SRV Refusals", ""]) + s70 = summary["slot70_refusals"] + s70_rows = [ + [count, reason, dim, fmt, vdim, vfmt, layout, flags] + for (reason, dim, fmt, vdim, vfmt, layout, flags), count in s70.most_common() + ] + out.extend( + _format_table( + ["Count", "Reason", "Res Dim", "Res Fmt", "View Dim", "View Fmt", "Layout", "Flags"], + s70_rows, + len(s70), + sum(s70.values()), + max_items, + ) + ) + + # 2. x2w-d3d12 unhandled/stubbed calls & traps + out.extend(["### Unhandled / Stubbed `x2w-d3d12` & Trap Calls", ""]) + d3d = summary["d3d12_unhandled"] + d3d_rows = [[count, f"`{call}`"] for call, count in d3d.most_common()] + out.extend( + _format_table( + ["Count", "Call / Slot"], + d3d_rows, + len(d3d), + sum(d3d.values()), + max_items, + ) + ) + + # 3. x2w-d3d12-debug + dbg = summary["d3d12_debug"] + if dbg: + out.extend(["### `x2w-d3d12-debug` Messages", ""]) + dbg_rows = [ + [count, ctx, sev, msg_id, msg] + for (ctx, sev, msg_id, msg), count in dbg.most_common() + ] + out.extend( + _format_table( + ["Count", "Context", "Sev", "ID", "Message (redacted)"], + dbg_rows, + len(dbg), + sum(dbg.values()), + max_items, + ) + ) + + # 4. x2w-dstorage failures & HRESULTs + out.extend(["### `x2w-dstorage` Failures & Status HRESULTs", ""]) + ds_fail = summary["dstorage_failures"] + ds_rows = [[count, reason] for reason, count in ds_fail.most_common()] + out.extend( + _format_table( + ["Count", "Failure Reason"], + ds_rows, + len(ds_fail), + sum(ds_fail.values()), + max_items, + ) + ) + ds_hr = summary["dstorage_hresults"] + if ds_hr: + hr_rows = [[count, f"`{hr}`"] for hr, count in ds_hr.most_common()] + out.extend( + _format_table( + ["Count", "Status HRESULT"], + hr_rows, + len(ds_hr), + sum(ds_hr.values()), + max_items, + ) + ) + + # 5. x2w-runtime failing methods / HRESULTs + out.extend(["### `x2w-runtime` Failing Methods", ""]) + rt = summary["runtime_failures"] + rt_rows = [[count, f"`{method}`", f"`{hr}`"] for (method, hr), count in rt.most_common()] + out.extend( + _format_table( + ["Count", "Method", "HRESULT / Status"], + rt_rows, + len(rt), + sum(rt.values()), + max_items, + ) + ) + + # 6. X2W_SHADER_CACHE .fail reasons + if shader_cache_provided: + out.extend(["### `X2W_SHADER_CACHE` `.fail` Reasons", ""]) + sh_rows = [[count, f"`{reason}`"] for reason, count in shader_failures.most_common()] + out.extend( + _format_table( + ["Count", "Reason"], + sh_rows, + len(shader_failures), + sum(shader_failures.values()), + max_items, + ) + ) + + return "\n".join(out) + + +def triage_run( + logdir: Path, + shader_cache: Path | None = None, + max_items: int = 16, +) -> str: + """Scan logdir (and optional shader_cache) and return a redacted Markdown summary.""" + log_files = iter_log_files(logdir) + + def _line_stream() -> Iterable[str]: + for path in log_files: + try: + with path.open("r", encoding="utf-8", errors="replace") as handle: + yield from handle + except OSError: + continue + + summary = summarize_lines(_line_stream()) + shader_failures = summarize_shader_cache(shader_cache) + return format_markdown( + summary=summary, + shader_failures=shader_failures, + files_scanned=len(log_files), + shader_cache_provided=shader_cache is not None, + max_items=max(1, max_items), + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Summarize startup logs and optional shader cache into redacted Markdown." + ) + parser.add_argument("logdir", type=Path, help="Startup log directory or single log file") + parser.add_argument( + "--shader-cache", + type=Path, + default=None, + help="Optional X2W_SHADER_CACHE directory containing *.fail files", + ) + parser.add_argument( + "--max-items", + type=int, + default=16, + help="Maximum rows per summary table (default: 16)", + ) + args = parser.parse_args(argv) + print(triage_run(args.logdir, shader_cache=args.shader_cache, max_items=args.max_items)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From d27560cf45aac5e6cfb90969159fc643a3784b71 Mon Sep 17 00:00:00 2001 From: sydney-0o <215686885+sydney-0o@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:59:48 +0500 Subject: [PATCH 074/775] tooling: report frame heartbeats without guessing draw status --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + tests/startup_live_view_check.py | 34 ++++++++++++++++++++++++++++++++ tools/startup/live_view.py | 5 +++-- 4 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 tests/startup_live_view_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b73d82490..cb04139fc 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -111,6 +111,7 @@ jobs: python -B tests/startup_image_load_mip_check.py python -B tests/startup_image_2d_array_check.py python -B tests/startup_host_cpu_check.py + python -B tests/startup_live_view_check.py python -B tests/startup_translator_check.py python -B tests/startup_flat_param_check.py python -B tests/startup_inline_sampler_check.py diff --git a/AGENTS.md b/AGENTS.md index 8123a2110..85d31089b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -145,6 +145,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_load_mip_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_host_cpu_check.py +./out/pe-env/bin/python -B tests/startup_live_view_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_flat_param_check.py ./out/pe-env/bin/python -B tests/startup_inline_sampler_check.py diff --git a/tests/startup_live_view_check.py b/tests/startup_live_view_check.py new file mode 100644 index 000000000..0317788c9 --- /dev/null +++ b/tests/startup_live_view_check.py @@ -0,0 +1,34 @@ +"""Check that the live viewer reports only what a frame heartbeat establishes.""" + +import contextlib +import io +from pathlib import Path +import runpy +import sys +import tempfile +import unittest +from unittest import mock + + +class LiveViewCheck(unittest.TestCase): + def test_frame_heartbeat_does_not_claim_draws_were_dropped(self): + viewer = Path(__file__).resolve().parents[1] / "tools" / "startup" / "live_view.py" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "trap.log").write_text( + "x2w-d3d12 heartbeat: 60 frames presented in 2.0 s (30.0 fps overall)\n", + encoding="utf-8", + ) + (root / "finished.txt").write_text("finished\n", encoding="utf-8") + output = io.StringIO() + with mock.patch.object(sys, "argv", [str(viewer), directory]), \ + mock.patch("os.system"), mock.patch("time.sleep"), \ + contextlib.redirect_stdout(output): + runpy.run_path(str(viewer), run_name="__main__") + + self.assertIn("60 frames presented, 30.0 fps", output.getvalue()) + self.assertNotIn("every draw dropped", output.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/startup/live_view.py b/tools/startup/live_view.py index eef06ef42..231780fef 100644 --- a/tools/startup/live_view.py +++ b/tools/startup/live_view.py @@ -92,7 +92,7 @@ def on_shim(line): m = re.search(r"heartbeat: (\d+) frames presented in ([\d.]+) s \(([\d.]+) fps", line) if m: frames = m.group(1) - say("frames", f"{m.group(1)} frames presented, {m.group(3)} fps (every draw dropped: no GPU translation yet)") + say("frames", f"{m.group(1)} frames presented, {m.group(3)} fps") elif "title main state" in line: m = re.search(r"state (-?\d+) -> (-?\d+)", line) if m: @@ -157,7 +157,8 @@ def on_shim(line): time.sleep(0.25) print("-" * 110) try: - print(open(finished, encoding="utf-8", errors="replace").read().strip()) + with open(finished, encoding="utf-8", errors="replace") as handle: + print(handle.read().strip()) except OSError: pass print("\nRun ended. Full logs are in " + os.path.abspath(rundir) + " (events.txt, files.txt, trap.log).") From 767a07836ec995f93aa93d3550c7ef9dee05b54d Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:02:38 +0800 Subject: [PATCH 075/775] docs: record the compute-produced mesh texture on Intel Xe2 The paragraph lists the GTX 1060 and in-box WARP across 128 export bytes and 1,024 pixels with one and two producers, plus a 276-pixel stale-binding control. Append the Intel Arc 140T at 8f51708e: both producer cases matched and the same control changed exactly 276 pixels with matching exports, with zero debug errors and warnings. Docs only. --- docs/experiments.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index 549549b85..3b4735c4c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2715,7 +2715,11 @@ The GTX 1060 and Windows 10 in-box WARP matched all 128 export bytes and all 1,024 pixels with one producer and with the second of two producers selected. Selecting the first texture against the second texture's reference changed exactly 276 pixels while the exports matched. The debug layer reported zero -warnings and errors. +warnings and errors. On Windows 11 build 26300.9974, the Intel Arc 140T +(32.0.101.8132) matched the same 128 export bytes and 1,024 pixels with one +producer and with the second of two producers selected, and the stale-binding +control changed exactly 276 pixels with matching exports, again with zero +D3D12 debug errors and warnings. ```powershell ctest --preset dev --no-tests=error -R '^compute_mesh_texture_fallback_' -V From 1e788c6f247cbd7a750e968e22ee6bc84cdd2fc6 Mon Sep 17 00:00:00 2001 From: Roan System Labs Date: Tue, 24 Nov 2026 12:39:00 +0100 Subject: [PATCH 076/775] tooling: add counted-loop generators to the CPU fuzz test Refs #446. Adds cpu_aot_fuzz_loops with its own seed: counted loops that end in a backward conditional branch (DEC/SUB and JNZ, DEC and JNS, INC/CMP and JB/JNE/JL, a guarded zero-trip form, SUB by 2 or 3 and JG), values carried between iterations in registers, in pushed nonvolatile registers and in the output buffer, data-dependent early exits and a nested loop whose inner count comes from a carried value. Every count is masked, so each input terminates. A planted back_edge_exit mutant, which retargets every backward conditional branch to its fallthrough, must be detected. The other areas' emitted MASM and translations are unchanged. --- CMakeLists.txt | 41 +++++++++++++ docs/experiments.md | 2 + tools/fuzz_cpu.py | 144 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 185 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 480656a3b..56df4e925 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1925,6 +1925,47 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$" "${cpu_fuzz_rsp_o2}" --area rsp --mutant "$") set_tests_properties(cpu_aot_fuzz_rsp PROPERTIES TIMEOUT 60) + + # Counted loops with backward conditional branches, early exits and a nested loop, with every back edge retargeted planted. + set(CPU_FUZZ_LOOPS_SEED "0x100F" CACHE STRING "Seed for the CPU differential fuzz loop test") + set(CPU_FUZZ_LOOPS_FUNCTIONS "32" CACHE STRING "Number of exported functions in the CPU differential fuzz loop test") + set(cpu_fuzz_loops_asm "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_loops.asm") + set(cpu_fuzz_loops_def "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_loops.def") + add_custom_command(OUTPUT "${cpu_fuzz_loops_asm}" "${cpu_fuzz_loops_def}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" emit + "${CPU_FUZZ_LOOPS_SEED}" "${CPU_FUZZ_LOOPS_FUNCTIONS}" "${cpu_fuzz_loops_asm}" + "${cpu_fuzz_loops_def}" --area loops + DEPENDS tools/fuzz_cpu.py VERBATIM) + add_library(cpu_fuzz_loops SHARED "${cpu_fuzz_loops_asm}" "${cpu_fuzz_loops_def}") + set_target_properties(cpu_fuzz_loops PROPERTIES LINKER_LANGUAGE CXX) + target_link_options(cpu_fuzz_loops PRIVATE /NOENTRY /NODEFAULTLIB /INCREMENTAL:NO /OPT:NOICF) + set(cpu_fuzz_loops_lifted "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_loops_lifted.cpp") + set(cpu_fuzz_loops_mutant "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_loops_mutant.cpp") + foreach(variant lifted mutant) + set(mutant_flag "") + if(variant STREQUAL "mutant") + set(mutant_flag "--mutant") + endif() + add_custom_command(OUTPUT "${cpu_fuzz_loops_${variant}}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" translate + "${CPU_FUZZ_LOOPS_SEED}" "${CPU_FUZZ_LOOPS_FUNCTIONS}" "$" + "${cpu_fuzz_loops_${variant}}" --area loops ${mutant_flag} + DEPENDS cpu_fuzz_loops tools/fuzz_cpu.py tools/cpu_switch_aot.py tools/cpu_leaf_aot.py + tools/cpu_call_aot.py tools/cpu_ranges.py VERBATIM) + add_library(cpu_fuzz_loops_${variant} SHARED "${cpu_fuzz_loops_${variant}}") + target_compile_features(cpu_fuzz_loops_${variant} PRIVATE cxx_std_20) + endforeach() + set(cpu_fuzz_loops_o2 "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_loops_lifted_o2.dll") + add_custom_command(OUTPUT "${cpu_fuzz_loops_o2}" + COMMAND "${CMAKE_CXX_COMPILER}" /nologo /O2 /W4 /LD "${cpu_fuzz_loops_lifted}" + "/Fo${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_loops_lifted_o2.obj" "/Fe${cpu_fuzz_loops_o2}" + DEPENDS "${cpu_fuzz_loops_lifted}" VERBATIM) + add_custom_target(cpu_fuzz_loops_lifted_o2 ALL DEPENDS "${cpu_fuzz_loops_o2}") + add_test(NAME cpu_aot_fuzz_loops COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" check "${CPU_FUZZ_LOOPS_SEED}" "${CPU_FUZZ_LOOPS_FUNCTIONS}" + "$" "$" "${cpu_fuzz_loops_o2}" + --area loops --mutant "$") + set_tests_properties(cpu_aot_fuzz_loops PROPERTIES TIMEOUT 60) cpu_asm_fixture(cpu_switch_addr32 switch_addr32) cpu_asm_fixture(cpu_switch_strings switch_strings) cpu_asm_fixture(cpu_string_probe string_probe) diff --git a/docs/experiments.md b/docs/experiments.md index 5f7a5182d..b739e60f1 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2512,6 +2512,8 @@ Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_smoke$' -V`. `CPU_FUZ `cpu_aot_fuzz_rsp` (`--area rsp`) covers mid-body RSP changes in the [translator](../tools/cpu_switch_aot.py) from its own seed, so the areas above are unchanged (their `emit` output is byte-identical to the previous revision at the default and the documented long-run seeds). Each export is fn(x, y, out). Its prologue pushes one to three of RBX, RSI, RDI and R12 to R15 and allocates 16 to 48 bytes, with the matching unwind directives, and every saved register is overwritten from RCX and RDX before it is read. After the prologue the body moves RSP again: `SUB RSP` and `ADD RSP` by 8 to 48 bytes, `PUSH` and `POP` of saved registers that hold data (a `POP` may load bytes that narrower stores wrote, or another register's pushed value), and stores, reloads and in-place updates of 1, 2, 4 or 8 bytes at any offset of the allocation, the caller's home space and what the body allocated itself. A reload prefers bytes that were stored at another RSP, so the same bytes are reached through different `[RSP+d]` displacements; every function has at least one such reload and four reloads in all, and every reloaded value goes to the output buffer and into RAX. The saved registers' final values are written to the buffer before the epilogue. The 36 default exports cycle through six shapes: adjustments only; mostly `PUSH` and `POP`; a `TEST` and a conditional jump whose two arms move RSP by the same amount in different ways (`SUB RSP` or `PUSH`, sometimes with an excursion that the arm releases again), so the join sees one depth and only the bytes both arms defined stay defined; a mid-body `SUB RSP` that aligns RSP for one or two direct calls to frameless callees that no export names, after which only RAX, the saved registers and the frame above the callee's home space are read; and two shapes with an RBP anchor (`PUSH RBP`, `MOV RBP, RSP`, `.setframe`) that address the same bytes through `[RBP+d]` and `[RSP+d]` at different depths and end with `LEAVE`, which releases whatever the body left allocated, or with `ADD RSP` and `POP RBP`. The generator follows which stack bytes are defined: the bytes that `ADD RSP` and `POP` release, and the callee's home space after a call, are never read again before they are written, because the translator treats them as undefined. RSP stays within 256 bytes below entry RSP. At the default seed `0xB0D1` the 36 exports have 110 mid-body `SUB RSP`, 77 mid-body `ADD RSP`, 52 mid-body `PUSH` and 13 mid-body `POP`, 11 branches, 10 calls, 6 `LEAVE` epilogues, 362 `[RSP+d]` and 72 `[RBP+d]` operands, and 168 reloads; 123 of the reloads and `POP` instructions read bytes stored at another RSP. Four negative controls in the same DLL are translated one at a time, and the test fails unless each is refused for its own reason: a reload of bytes that `ADD RSP` released and `SUB RSP` allocated again (`undefined stack byte`), a branch after which the two paths reach the join at different depths (`stack depth differs at join`), a read below RSP (`stack access below RSP`) and `SUB RSP, 4` (`unsupported stack adjustment`). The planted translator fault, `--mutant` (`stale_rsp`), resolves every `[RSP+d]` operand against the RSP that the prologue's allocation leaves, as if no later `SUB`, `ADD`, `PUSH` or `POP` had moved RSP; `PUSH`, `POP`, `[RBP+d]` operands and the frame proof are unchanged, and an operand whose moved bytes would leave the frame array keeps its index. The test fails unless that build differs from native. Measured on Windows 11 build 26300 with MSVC 19.51 (Visual Studio Build Tools, toolset 14.51) and ML64 14.51: at the default seed, 22,536 native, default and `/O2` comparisons matched in the `dev` and `release` presets, the four controls were refused, and the planted fault differed in 9,045 of 11,268 calls, in 31 of the 36 exports. The other five are two anchored exports that read through RBP and three calling exports whose moved operands would leave the frame array, where the fault keeps the index. Passing the clean translation as `--mutant` fails with `the planted translator fault was not detected`, and passing the mutant as the translation fails at the first mismatch with the reproduction command. Seeds `0x1`, `0x2`, `0xBEEF` and `0xCCD1` at 120 exports each made 75,120 comparisons with no refusal and no mismatch; the planted fault differed in 28,393, 30,027, 29,171 and 31,033 of 37,560 calls. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_rsp$' -V`. `CPU_FUZZ_RSP_SEED` and `CPU_FUZZ_RSP_FUNCTIONS` select a longer run. The generator does not use `MOV RSP, RBP`, `LEA RSP` or `ENTER` (the translator refuses them as a dynamic frame), an RBP anchor that moves after the prologue, stack arguments, calls in an anchored frame or fault equivalence. +`cpu_aot_fuzz_loops` (`--area loops`) covers counted loops on the shared [translator](../tools/cpu_switch_aot.py) from its own seed, so the areas above are unchanged (their `emit` output and translations are byte-identical to the previous revision). Every export ends its loop with a backward conditional branch and takes one of four forms: a counter from n down to 1 (`DEC` or `SUB 1`, then `JNZ`) or from n-1 down to 0 (`DEC`, then `JNS`); an index from 0 up to n-1 (`INC`, `CMP` with the count, then `JB`, `JNE` or `JL`); a counter that may start at 0, with a `TEST` and `JZ` in front that skips the loop; and a counter that drops by 2 or 3 while it stays above 0 (`SUB`, then `JG`). The count is x masked to four bits, plus one where the loop has no guard, and only the loop's own update writes the counter, so every input ends after at most 16 iterations. Each iteration updates RAX and one or two other registers from each other and from the counter (64- and 32-bit `ADD`, `SUB`, `XOR`, three-operand `IMUL`, `ROL`, `ROR`, `LEA`, `NOT` and `NEG`), so their values carry from one iteration to the next. Some exports first push one or two of RBX, RSI and RDI, carry a value in the first of them and pop them on both exits. A value also carries through the output buffer: the loop updates the qword at output offset 24 in place, reads it back into a register, adds one to an iteration count at offset 32 and writes RAX into a per-iteration slot from offset 64, indexed by the counter. Half the exports have a data-dependent early exit: a `TEST` of AL or R10D or an unsigned `CMP` of EAX with a constant leads to a second exit that records the counter (the count, in the up form) and returns another combination. Half nest a second loop inside the first: x masked to three bits, plus one, counts the outer loop, and the low three bits of the carried RAX, plus one, count the inner loop, so its trip count changes from one outer iteration to the next (at most 8 by 8). The inner loop adds R10 into a per-iteration slot from offset 192 and ends with `DEC` and `JNZ`. The 32 default exports at seed `0x100F` are the 16 combinations of form, nesting and early exit, twice, in a seeded order: 48 backward branches (32 outer and 16 inner), 16 exports with pushed registers. On its 313 inputs, the native exports take the early exit in 1,573 of 10,016 calls, skip the guarded loop in 632 and run the outer loop more than once in 6,380, up to 16 times. The test makes 20,032 native, default and `/O2` comparisons of RAX and the 256-byte output buffer in about 0.5 s. The planted translator fault, `--mutant` (`back_edge_exit`), retargets every backward conditional branch to its own fallthrough, so each loop body runs once and every input still terminates; the test fails unless that build differs from native. At the default seed it differed in 7,439 of 10,016 calls, in all 32 exports. Passing the clean translation as `--mutant` fails with `the planted translator fault was not detected`, and passing the mutant as the translation fails at the first mismatch with the export's MASM and the reproduction command. `CPU_FUZZ_LOOPS_SEED` and `CPU_FUZZ_LOOPS_FUNCTIONS` select a longer run. Seeds `0x1`, `0x2`, `0xBEEF` and `0xCCD1` at 128 exports each made 80,128 comparisons per seed in about 1.6 s, with no refusal and no mismatch; each has 192 backward branches, and the planted fault differed in 29,248 to 29,894 of 40,064 calls, in all 128 exports. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_loops$' -V`. The generator does not use loops whose count is not bounded by a mask, an unconditional backward `JMP`, `LOOP` or `REP` forms, frames with stack slots, calls inside a loop, or loops that share a head. + ## Mesh draw fallback The bounded mesh translator can emit `cs_6_0` entry `main` and `vs_6_0` entry diff --git a/tools/fuzz_cpu.py b/tools/fuzz_cpu.py index 73d6e7b03..cbba66a98 100644 --- a/tools/fuzz_cpu.py +++ b/tools/fuzz_cpu.py @@ -1457,10 +1457,120 @@ def generate_rsp(seed, count): return [*callees, *functions, *(rsp_control(f"fuzz_rsp_refused_{kind}", kind) for kind in RSP_CONTROLS)] +# Counted loops: leaf functions, some with pushed registers, whose loops end in a backward conditional branch. +# Every trip count comes from x masked to 4 bits (3 bits for a nested loop) and the counter is written only by +# the loop's own update, so each input terminates within 16 iterations, or 8 times 8 when nested. The output +# buffer keeps the final carried registers at 0 to 23, a value carried through memory at 24, an iteration count +# at 32, the final counter (the count in the up form) at 36, an early-exit record at 40 to 55, the first saved +# register at 56, one word per outer iteration from 64 to 191 and one word per inner iteration from 192 to 255. +LOOP_FORMS = ("dec", "up", "guarded", "step") +LOOP_CARRIED = ("rax", "rdx", "r10") +LOOP_SAVED = ("rbx", "rsi", "rdi") +LOOP_MEMORY, LOOP_COUNT, LOOP_FINAL, LOOP_EARLY, LOOP_SAVES, LOOP_TRACE, LOOP_INNER = 24, 32, 36, 40, 56, 64, 192 + + +def loop_operation(rng, target, sources): + """One update of a carried register from itself and the other carried values.""" + source = rng.choice(sources) + dword = rng.random() < 0.2 + a, b = (REGISTER_PARTS[target][0], REGISTER_PARTS[source][0]) if dword else (target, source) + return rng.choice((f"add {a}, {b}", f"sub {a}, {b}", f"xor {a}, {b}", f"imul {a}, {b}, {rng.choice((3, 5, 7, 31))}", + f"rol {target}, {rng.choice((5, 13, 29))}", f"ror {target}, {rng.choice((3, 11))}", + f"lea {target}, [{target}+{source}*{rng.choice((2, 4, 8))}+{rng.choice((1, 7, 0x51))}]", + f"add {a}, {REGISTER_PARTS['r9'][0] if dword else 'r9'}", f"not {target}", f"neg {target}")) + + +def loop_function(name, rng, form, nested, early): + """A counted loop of one of four forms, with an optional data-dependent early exit and nested loop. + + dec: the counter runs from n down to 1 (DEC or SUB 1, then JNZ) or from n-1 down to 0 (DEC, then JNS). + up: an index runs from 0 up to n-1 (INC, CMP with the count, then JB, JNE or JL). + guarded: as dec from n, but n may be 0 and a TEST and JZ in front skips the loop. + step: the counter drops by 2 or 3 while it stays above 0 (SUB, then JG). + """ + saved = rng.sample(LOOP_SAVED, rng.choice((0, 0, 1, 2))) + prolog = [line for register in saved for line in (f"push {register}", f".pushreg {register}")] + carried = [*LOOP_CARRIED, *saved] + top, exit_, out = f"{name}_top", f"{name}_exit", f"{name}_early" + # The count n is x masked, plus 1 where the loop has no guard; a dec loop that ends at 0 starts from n-1. + to_zero = form == "dec" and rng.random() < 0.5 + lines = ["mov r9d, ecx", f"and r9d, {7 if nested else 15}"] + if form != "guarded" and not to_zero: + lines.append("inc r9d") + # Carried values defined from both arguments; each saved register is overwritten before it is read. + lines += ["mov rax, rcx", "lea r10, [rdx+rcx*2+3]", f"mov QWORD PTR [r8+{LOOP_MEMORY}], rdx", + f"mov DWORD PTR [r8+{LOOP_COUNT}], 0"] + for register in saved: + lines += [f"mov {register}, rdx", rng.choice((f"xor {register}, rcx", f"rol {register}, 17", f"add {register}, rcx"))] + if form == "up": + lines.append("xor r11d, r11d") + if form == "guarded": + lines += ["test r9d, r9d", f"jz {exit_}"] + # The outer trace: one word per iteration indexed by the counter or index, from LOOP_TRACE. + if form == "up": + trace = f"mov QWORD PTR [r8+r11*8+{LOOP_TRACE}], rax" + elif to_zero: + trace = f"mov QWORD PTR [r8+r9*8+{LOOP_TRACE}], rax" + else: + trace = f"mov QWORD PTR [r8+r9*8+{LOOP_TRACE - 8}], rax" + + # RAX and a saved register, when there is one, change in every iteration. + targets = ["rax", *saved[:1], *rng.sample(carried, rng.choice((1, 2)))] + body = [loop_operation(rng, target, [r for r in carried if r != target]) for target in targets] + body.append(rng.choice((f"add QWORD PTR [r8+{LOOP_MEMORY}], rax", f"xor QWORD PTR [r8+{LOOP_MEMORY}], r10", + f"sub QWORD PTR [r8+{LOOP_MEMORY}], rdx"))) + body.append(rng.choice((f"add rax, QWORD PTR [r8+{LOOP_MEMORY}]", f"xor r10, QWORD PTR [r8+{LOOP_MEMORY}]", + f"add rdx, QWORD PTR [r8+{LOOP_MEMORY}]"))) + body += [f"add DWORD PTR [r8+{LOOP_COUNT}], 1", trace] + if early: + producer = rng.choice((f"test al, {rng.choice((3, 7))}", f"test r10d, {rng.choice((0xF, 0x1F))}", + f"cmp eax, {rng.choice((0x10000000, 0x20000000))}")) + # After the first update, so the flags never cross the loop head. + at = rng.randrange(1, len(body) + 1) + body[at:at] = [producer, f"{'jb' if producer.startswith('cmp') else 'jz'} {out}"] + if nested: + # The inner count comes from the carried RAX, so it differs from one outer iteration to the next. + inner = f"{name}_inner" + body += ["mov ecx, eax", "and ecx, 7", "inc ecx", f"{inner}:", + *(loop_operation(rng, target, [r for r in carried if r != target]) + for target in rng.sample(carried, rng.choice((1, 2)))), + f"add QWORD PTR [r8+rcx*8+{LOOP_INNER - 8}], r10", "dec ecx", f"jnz {inner}"] + if form == "dec": + if to_zero: + body += ["dec r9d", f"jns {top}"] + else: + body += [rng.choice(("dec r9d", "sub r9d, 1")), f"jnz {top}"] + elif form == "guarded": + body += ["dec r9d", f"jnz {top}"] + elif form == "step": + body += [f"sub r9d, {rng.choice((2, 3))}", f"jg {top}"] + else: + body += ["inc r11d", "cmp r11d, r9d", f"{rng.choice(('jb', 'jne', 'jl'))} {top}"] + + restore = [f"pop {register}" for register in reversed(saved)] + stores = [f"mov QWORD PTR [r8+{LOOP_SAVES}], {saved[0]}", f"add rax, {saved[0]}"] if saved else ["xor rax, r10"] + lines += [f"{top}:", *body, f"{exit_}:", "mov QWORD PTR [r8], rax", "mov QWORD PTR [r8+8], r10", + "mov QWORD PTR [r8+16], rdx", f"mov DWORD PTR [r8+{LOOP_FINAL}], r9d", *stores, *restore, "ret"] + if early: + lines += [f"{out}:", f"mov DWORD PTR [r8+{LOOP_EARLY}], 0EA51h", f"mov QWORD PTR [r8+{LOOP_EARLY + 8}], r9", + "mov QWORD PTR [r8+16], rdx", "lea rax, [rax+r10*2]", *restore, "ret"] + return Function(name, lines, prolog) + + +def generate_loops(seed, count): + """Exports with counted loops: the 16 combinations of form, nesting and early exit in a seeded order, + repeated with other bodies.""" + rng = random.Random(seed) + shapes = [(form, nested, early) for form in LOOP_FORMS for nested in (False, True) for early in (False, True)] + rng.shuffle(shapes) + return [loop_function(f"fuzz_loop_{index}", rng, *shapes[index % len(shapes)]) for index in range(count)] + + AREAS = {"leaf": (generate, "cpu_fuzz"), "frames": (generate_frames, "cpu_fuzz_frames"), "calls": (generate_calls, "cpu_fuzz_calls"), "chains": (generate_chains, "cpu_fuzz_chains"), "switches": (generate_switches, "cpu_fuzz_switches"), - "scalar_fp": (generate_scalar_fp, "cpu_fuzz_scalar_fp"), "rsp": (generate_rsp, "cpu_fuzz_rsp")} + "scalar_fp": (generate_scalar_fp, "cpu_fuzz_scalar_fp"), "rsp": (generate_rsp, "cpu_fuzz_rsp"), + "loops": (generate_loops, "cpu_fuzz_loops")} def inputs_for(seed, area="leaf", signature=None): @@ -1792,10 +1902,40 @@ def slot(self, ins): cpu_switch_aot.Lifter.slot = slot +def plant_back_edge_exit(cpu_switch_aot, image, functions): + """Retarget every backward conditional branch to its own fallthrough, the instruction after the loop. + + This is a planted translator fault for the negative control: each loop body runs once, so any input + with more than one iteration leaves another trace, count and carried value. Every input still terminates. + """ + from iced_x86 import FlowControl + + original = cpu_switch_aot.Function.decode + planted = [] + + def decode(self, ip): + ins = original(self, ip) + if ins.flow_control == FlowControl.CONDITIONAL_BRANCH and ins.near_branch_target <= ip: + ins.near_branch64 = ins.next_ip + planted.append(ip) + return ins + + cpu_switch_aot.Function.decode = decode + translate_original = cpu_switch_aot.translate + + def translate(*args, **kwargs): + result = translate_original(*args, **kwargs) + if not planted: + raise SystemExit("the back_edge_exit fault found no backward branch") + return result + + cpu_switch_aot.translate = translate + + MUTANTS = {"frames": ("reload_shift", plant_reload_shift), "calls": ("call_retarget", plant_call_retarget), "chains": ("swapped_arguments", plant_swapped_arguments), "switches": ("table_rotate", plant_table_rotate), "scalar_fp": ("minmax_swap", plant_minmax_swap), - "rsp": ("stale_rsp", plant_stale_rsp)} + "rsp": ("stale_rsp", plant_stale_rsp), "loops": ("back_edge_exit", plant_back_edge_exit)} def translate(seed, count, image, output, area="leaf", mutant=False): From 666773411aa8919ba5e262eac4627a0e0dd7f737 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:05:12 +0100 Subject: [PATCH 077/775] startup_stubs/audio_sink: fold to mono before clamping and keep resampler state across blocks --- src/startup_stubs/audio_sink.cpp | 14 ++-- src/startup_stubs/audio_sink.h | 113 ++++++++++++++++++++++++------- tests/startup_audio_output.cpp | 3 +- tests/startup_audio_pure_check.h | 48 +++++++++++++ 4 files changed, 146 insertions(+), 32 deletions(-) diff --git a/src/startup_stubs/audio_sink.cpp b/src/startup_stubs/audio_sink.cpp index bdc6d101c..c8fde0258 100644 --- a/src/startup_stubs/audio_sink.cpp +++ b/src/startup_stubs/audio_sink.cpp @@ -124,7 +124,8 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt { const uint32_t call = calls_++; if (!p_) return Submit::NotOpen; - if (!convert_block(in, bytes, frames, mix_, conv_buf_)) { + ResampleState trial = resample_; // committed only once the block is accepted + if (!convert_block(in, bytes, frames, mix_, conv_buf_, &trial)) { ++r_.unsupported; return Submit::Unsupported; } @@ -137,10 +138,13 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt } observe(false); if (timer_.drained_start >= 0) timer_.resume(now_ms(), r_.consumed_frames); // the producer is back - BYTE* dst = nullptr; - if (FAILED(p_->render->GetBuffer(out_frames, &dst)) || !dst) return Submit::NotOpen; - std::memcpy(dst, conv_buf_.data(), conv_buf_.size()); - if (FAILED(p_->render->ReleaseBuffer(out_frames, 0))) return Submit::NotOpen; + if (out_frames > 0) { + BYTE* dst = nullptr; + if (FAILED(p_->render->GetBuffer(out_frames, &dst)) || !dst) return Submit::NotOpen; + std::memcpy(dst, conv_buf_.data(), conv_buf_.size()); + if (FAILED(p_->render->ReleaseBuffer(out_frames, 0))) return Submit::NotOpen; + } + resample_ = std::move(trial); if (r_.first_block < 0) { r_.first_block = call; r_.submitted = in; diff --git a/src/startup_stubs/audio_sink.h b/src/startup_stubs/audio_sink.h index ff00efde7..4f71bac2a 100644 --- a/src/startup_stubs/audio_sink.h +++ b/src/startup_stubs/audio_sink.h @@ -9,6 +9,7 @@ #include #include #include +#include #include namespace x2w_audio { @@ -102,10 +103,9 @@ inline float read_channel_mapped_sample(const BlockFormat& in, const void* src, left += kItuSurroundCoeff * sl; right += kItuSurroundCoeff * sr; } - left = std::clamp(left, -1.0f, 1.0f); - right = std::clamp(right, -1.0f, 1.0f); + // Mono: average the unclipped stereo sums, clamp only the final value. if (out_channels == 1u) return std::clamp(0.5f * (left + right), -1.0f, 1.0f); - return out_ch == 0u ? left : right; + return std::clamp(out_ch == 0u ? left : right, -1.0f, 1.0f); } inline uint32_t resampled_frame_count(uint32_t frames, uint32_t in_rate, uint32_t out_rate) @@ -118,50 +118,110 @@ inline uint32_t resampled_frame_count(uint32_t frames, uint32_t in_rate, uint32_ return static_cast(scaled); } +// Resampler memory carried between accepted blocks of one stream: the exact fractional read +// position (in 1/out_rate input-frame units, relative to the next block's first frame; -out_rate +// <= phase_num means the next output sits between `last` and the next block's first frame) and the +// last channel-mapped input frame. Cleared on any input/output format change. +struct ResampleState { + bool valid = false; + BlockFormat in{}, out{}; + int64_t phase_num = 0; + std::vector last; + void reset() { *this = ResampleState{}; } +}; + // Converts a submitted block to the endpoint format, supporting mono/stereo/5.1/7.1 channel mapping -// (ITU-R BS.775-1 fold-down with clamping) and linear sample-rate resampling. +// (ITU-R BS.775-1 fold-down, clamped after the final fold-down) and linear sample-rate resampling. // Preserves exact bit-for-bit behavior for matching-rate 1:1 and mono-to-N paths. +// With state == nullptr each block is converted on its own (tail frames clamp to the last input +// frame). With a state, consecutive blocks form one stream: the fractional phase and the boundary +// frame carry over, so the output does not depend on how the input was split into blocks; the +// final interpolation point waits for the next block, so a block may yield fewer (even zero) +// frames and convert_block then returns true with an empty dst. inline bool convert_block(const BlockFormat& in, const void* src, uint32_t frames, const BlockFormat& out, - std::vector& dst) + std::vector& dst, ResampleState* state = nullptr) { if (!src || frames == 0) return false; if (!is_valid_sample_rate(in.rate) || !is_valid_sample_rate(out.rate)) return false; if (!is_supported_channel_conversion(in.channels, out.channels)) return false; - const uint32_t out_frames = resampled_frame_count(frames, in.rate, out.rate); - if (out_frames == 0) return false; - const uint64_t total_bytes = static_cast(out_frames) * out.frame_bytes(); - if (total_bytes > (std::numeric_limits::max)()) return false; - dst.resize(static_cast(total_bytes)); + const bool same_rate = in.rate == out.rate; + const bool carry = state && !same_rate; + if (state && (!state->valid || state->in.kind != in.kind || state->in.channels != in.channels || + state->in.rate != in.rate || state->out.kind != out.kind || + state->out.channels != out.channels || state->out.rate != out.rate || same_rate)) + state->reset(); + + if (!carry) { + const uint32_t out_frames = resampled_frame_count(frames, in.rate, out.rate); + if (out_frames == 0) return false; + const uint64_t total_bytes = static_cast(out_frames) * out.frame_bytes(); + if (total_bytes > (std::numeric_limits::max)()) return false; + dst.resize(static_cast(total_bytes)); - if (in.rate == out.rate) { - if (in.channels == out.channels || in.channels == 1u) { + if (same_rate) { + if (in.channels == out.channels || in.channels == 1u) { + for (size_t f = 0; f < frames; ++f) + for (size_t c = 0; c < out.channels; ++c) + write_sample(out, dst.data(), f * out.channels + c, + read_sample(in, src, f * in.channels + (in.channels == 1u ? 0 : c))); + return true; + } for (size_t f = 0; f < frames; ++f) - for (size_t c = 0; c < out.channels; ++c) + for (uint32_t c = 0; c < out.channels; ++c) write_sample(out, dst.data(), f * out.channels + c, - read_sample(in, src, f * in.channels + (in.channels == 1u ? 0 : c))); + read_channel_mapped_sample(in, src, f, c, out.channels)); return true; } - for (size_t f = 0; f < frames; ++f) - for (uint32_t c = 0; c < out.channels; ++c) - write_sample(out, dst.data(), f * out.channels + c, - read_channel_mapped_sample(in, src, f, c, out.channels)); + + const double step = static_cast(in.rate) / static_cast(out.rate); + for (uint32_t f = 0; f < out_frames; ++f) { + const double pos = static_cast(f) * step; + const uint32_t i0 = (std::min)(static_cast(pos), frames - 1u); + const uint32_t i1 = (std::min)(i0 + 1u, frames - 1u); + const float frac = static_cast(pos - static_cast(i0)); + for (uint32_t c = 0; c < out.channels; ++c) { + const float s0 = read_channel_mapped_sample(in, src, i0, c, out.channels); + const float s1 = (i1 == i0) ? s0 : read_channel_mapped_sample(in, src, i1, c, out.channels); + const float interp = std::clamp(s0 + frac * (s1 - s0), -1.0f, 1.0f); + write_sample(out, dst.data(), static_cast(f) * out.channels + c, interp); + } + } return true; } - const double step = static_cast(in.rate) / static_cast(out.rate); - for (uint32_t f = 0; f < out_frames; ++f) { - const double pos = static_cast(f) * step; - const uint32_t i0 = (std::min)(static_cast(pos), frames - 1u); - const uint32_t i1 = (std::min)(i0 + 1u, frames - 1u); - const float frac = static_cast(pos - static_cast(i0)); + // Streaming path. Output n reads input position n * in_rate / out_rate; phase_num is that + // position in 1/out_rate units relative to this block's first frame (may be negative). + const int64_t orate = out.rate; + const int64_t span = static_cast(frames) * orate; + int64_t phase = state->valid ? state->phase_num : 0; + // Emit while the right-hand neighbour (floor(pos) + 1) lies inside this block: pos < frames - 1. + int64_t count = 0; + if (phase < span - orate) count = (span - orate - phase + in.rate - 1) / in.rate; + const uint64_t total_bytes = static_cast(count) * out.frame_bytes(); + if (count > static_cast((std::numeric_limits::max)()) || + total_bytes > (std::numeric_limits::max)()) + return false; + dst.resize(static_cast(total_bytes)); + const bool have_last = state->valid && state->last.size() == out.channels; + for (int64_t f = 0; f < count; ++f, phase += in.rate) { + const int64_t base = phase >= 0 ? phase / orate : -((-phase + orate - 1) / orate); + const float frac = static_cast(static_cast(phase - base * orate) / static_cast(orate)); for (uint32_t c = 0; c < out.channels; ++c) { - const float s0 = read_channel_mapped_sample(in, src, i0, c, out.channels); - const float s1 = (i1 == i0) ? s0 : read_channel_mapped_sample(in, src, i1, c, out.channels); + const float s0 = base < 0 ? (have_last ? state->last[c] : 0.0f) + : read_channel_mapped_sample(in, src, static_cast(base), c, out.channels); + const float s1 = read_channel_mapped_sample(in, src, static_cast(base + 1), c, out.channels); const float interp = std::clamp(s0 + frac * (s1 - s0), -1.0f, 1.0f); write_sample(out, dst.data(), static_cast(f) * out.channels + c, interp); } } + state->in = in; + state->out = out; + state->phase_num = phase - span; + state->last.assign(out.channels, 0.0f); + for (uint32_t c = 0; c < out.channels; ++c) + state->last[c] = read_channel_mapped_sample(in, src, frames - 1u, c, out.channels); + state->valid = true; return true; } @@ -244,6 +304,7 @@ class AudioSink { Report r_; StarvationTimer timer_; std::vector conv_buf_; + ResampleState resample_; }; #endif diff --git a/tests/startup_audio_output.cpp b/tests/startup_audio_output.cpp index 15763a3ce..d95dc1953 100644 --- a/tests/startup_audio_output.cpp +++ b/tests/startup_audio_output.cpp @@ -148,7 +148,8 @@ int run() if (d.submit(ch6_44, 441, blk6.data()) != Submit::Accepted) return fail("case d 5.1 44.1 kHz block not accepted", 13); const Report rd = d.report(); - if (rd.unsupported != 1 || rd.submitted_frames != resampled_frame_count(441, 44100, mix.rate)) + if (rd.unsupported != 1 || rd.submitted_frames + 2 < resampled_frame_count(441, 44100, mix.rate) || + rd.submitted_frames > resampled_frame_count(441, 44100, mix.rate)) return fail("case d report counts mismatch", 14); } std::puts("startup_audio_output: PASS (no capture-path verification; glitch count not available from the render API)"); diff --git a/tests/startup_audio_pure_check.h b/tests/startup_audio_pure_check.h index 3c650936a..17c4a1b7a 100644 --- a/tests/startup_audio_pure_check.h +++ b/tests/startup_audio_pure_check.h @@ -112,6 +112,54 @@ inline int check_pure() if (std::fabs(read_sample(stereo_f, out.data(), 1) - exp_r) > 1e-5f) return 49; } + // Mono fold-down clamps only the final value: FL=1, FR=-1, FC=1 -> sqrt(0.5), not 0.3536. + { + const BlockFormat ch6_f{SampleKind::Float32, 6, 48000}; + const float fold[6] = {1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f}; + if (!convert_block(ch6_f, fold, 1, mono_f, out) || out.size() != 4) return 60; + if (std::fabs(read_sample(mono_f, out.data(), 0) - 0.5f * kItuSurroundCoeff * 2.0f) > 1e-5f) return 61; + // Stereo targets still clamp each channel (FL = 1 + 0.7071 clips to 1). + if (!convert_block(ch6_f, fold, 1, stereo_f, out) || out.size() != 8) return 62; + if (read_sample(stereo_f, out.data(), 0) != 1.0f) return 63; + } + + // Streaming resampler: output must not depend on how the input is split into blocks. + { + const BlockFormat in44{SampleKind::Float32, 1, 44100}; + std::vector ramp(44100); + for (size_t i = 0; i < ramp.size(); ++i) ramp[i] = static_cast(i) / 50000.0f; + std::vector whole, piece; + ResampleState one, many; + if (!convert_block(in44, ramp.data(), 44100, mono_f, whole, &one)) return 64; + std::vector joined; + for (size_t at = 0; at < ramp.size(); at += 128) { + const uint32_t n = static_cast((std::min)(size_t{128}, ramp.size() - at)); + if (!convert_block(in44, ramp.data() + at, n, mono_f, piece, &many)) return 65; + joined.insert(joined.end(), piece.begin(), piece.end()); + } + if (joined.size() != whole.size()) return 66; + for (size_t i = 0; i < whole.size() / 4; ++i) + if (std::fabs(read_sample(mono_f, joined.data(), i) - read_sample(mono_f, whole.data(), i)) > 1e-5f) return 67; + if (joined.size() / 4 < 48000 - 2 || joined.size() / 4 > 48000) return 68; // no per-block rounding drift + + // 24 -> 48 kHz ramp split at a boundary keeps the interpolation sample between the blocks. + const BlockFormat in24{SampleKind::Float32, 1, 24000}; + const float r8[8] = {0, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f}; + ResampleState st; + std::vector a, b; + if (!convert_block(in24, r8, 4, mono_f, a, &st) || !convert_block(in24, r8 + 4, 4, mono_f, b, &st)) return 69; + a.insert(a.end(), b.begin(), b.end()); + if (a.size() != 14 * 4) return 70; + for (size_t i = 0; i < 14; ++i) + if (std::fabs(read_sample(mono_f, a.data(), i) - 0.05f * static_cast(i)) > 1e-5f) return 71; + + // A format change drops the carried state: the new stream starts at its own first frame. + const BlockFormat in16{SampleKind::Float32, 1, 16000}; + const float flat[4] = {0.5f, 0.5f, 0.5f, 0.5f}; + if (!convert_block(in16, flat, 4, mono_f, a, &st)) return 72; + if (a.empty() || std::fabs(read_sample(mono_f, a.data(), 0) - 0.5f) > 1e-6f) return 73; + } + // Negative controls: 0 rate, out-of-range rate, 0 channels, unsupported channel count, empty block, null ptr. if (convert_block({SampleKind::Pcm16, 1, 0}, tone.data(), 480, mono_f, out)) return 50; if (convert_block(mono16, tone.data(), 480, {SampleKind::Float32, 1, 0}, out)) return 51; From 310ad97305a43f686bf323f2531881b1d06f9e01 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 20:06:09 +0800 Subject: [PATCH 078/775] Contain read-context allocation failures before XAsyncBegin --- src/startup_stubs/runtime_proxy.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index cf6de0df4..d0add93c0 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -623,8 +623,12 @@ u64 async_read(int slot, u64 container, u64 names, u64 count_or_size, u64 block_ } auto* async = reinterpret_cast(block_or_buffer); if (!async) return e_fail; - auto* state = new (std::nothrow) ReadAsync; - if (!state) return e_outofmemory; + ReadAsync* state; + try { + state = new ReadAsync; + } catch (const std::bad_alloc&) { + return e_outofmemory; + } using Begin = HRESULT(WINAPI*)(void*, void*, void*, const void*, const char*, decltype(&read_provider)); const auto begun = reinterpret_cast(methods[7])(service, async, state, read_identity, read_identity, read_provider); if (FAILED(begun)) { From 883bc7063ef8cae51265e838a1b8f17ae030bcb9 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:06:29 +0100 Subject: [PATCH 079/775] tests/startup_stream_depth: depth-only PSO has no pixel shader so zero-RTV pass raises no SV_Target0 warning --- tests/startup_stream_depth.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/startup_stream_depth.cpp b/tests/startup_stream_depth.cpp index a53bb611e..b7c42f562 100644 --- a/tests/startup_stream_depth.cpp +++ b/tests/startup_stream_depth.cpp @@ -221,10 +221,11 @@ int main(int argc, char** argv) void* pso_back_less = create_stream_pso(guest, root, vs_back, ps_red, ds_less, false); void* pso_front_off = create_stream_pso(guest, root, vs_front, ps_green, ds_disabled, false); void* pso_back_off = create_stream_pso(guest, root, vs_back, ps_red, ds_disabled, false); - void* pso_front_ds1 = create_stream_pso(guest, root, vs_front, ps_green, ds_less, true); + // Depth-only pass: no pixel shader, so nothing declares SV_Target0 for a zero-RTV bind. + void* pso_front_depth_only = create_stream_pso(guest, root, vs_front, {}, ds_less, true); // DepthBoundsTestEnable has no translated equivalent: the pipeline is refused for drawing, not translated without it. void* pso_front_bounds = create_stream_pso(guest, root, vs_front, ps_green, ds_less, true, TRUE); - if (!pso_front_bounds || !pso_front_less || !pso_back_less || !pso_front_off || !pso_back_off || !pso_front_ds1) return 9; + if (!pso_front_bounds || !pso_front_less || !pso_back_less || !pso_front_off || !pso_back_off || !pso_front_depth_only) return 9; if (argc == 7) return 0; ComPtr desktop; @@ -315,7 +316,7 @@ int main(int argc, char** argv) if (const int rc = run_case(1, argv[7], Bind::normal, pso_front_less, pso_back_less)) return rc; if (const int rc = run_case(2, argv[8], Bind::normal, pso_front_off, pso_back_off)) return rc; - if (const int rc = run_case(3, argv[9], Bind::depth_only, pso_front_ds1, pso_back_less)) return rc; + if (const int rc = run_case(3, argv[9], Bind::depth_only, pso_front_depth_only, pso_back_less)) return rc; if (const int rc = run_case(4, argv[10], Bind::read_only_depth, pso_front_less, pso_back_less)) return rc; // Controls: nothing may be drawn for a wrong descriptor kind or an enabled depth bounds test. if (const int rc = run_case(5, argv[11], Bind::rtv_as_depth, pso_front_less, pso_back_less)) return rc; From 3892513b071d0f9c5f380abb0ac1077084b5fa9e Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 20:06:06 +0800 Subject: [PATCH 080/775] shader: compare image LOD readback with direct HLSL --- docs/experiments.md | 10 +++- tests/desktop_gpu.h | 4 +- tests/offscreen_check.cpp | 9 +-- tests/pixel_aot_render.cpp | 29 ++++++--- tests/pixel_get_lod_check.py | 102 +++++++++++++++++++++++++++----- tests/pixel_get_lod_direct.hlsl | 21 +++++++ 6 files changed, 143 insertions(+), 32 deletions(-) create mode 100644 tests/pixel_get_lod_direct.hlsl diff --git a/docs/experiments.md b/docs/experiments.md index fa026b750..8c9c0d222 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -692,7 +692,15 @@ all exported channels, including the clamped LOD of zero. Clamping the raw result first differs at pixel `(0, 0)`, channel 1 (`-1` expected, `0` actual). A two-mip draw also checks clamped LOD 1 and raw LOD 2. Removing the upper clamp gives 2 in the channel that should contain 1. LLVM 15 assembles both -gfx1030 programs and round-trips them through the pixel container CLI. The GPU fixture executes the translated desktop DXIL. +gfx1030 programs and round-trips them through the pixel container CLI. +For each draw, the GPU fixture compiles the translated program and an +[independent HLSL program](../tests/pixel_get_lod_direct.hlsl) and runs both +with the same texture, sampler, viewport and constants. It compares all +256 FP32 channels and prints the first pixel's RGBA words and a SHA-256 +of the full readback for each path. The upper-clamp readback is in the +order `(raw LOD - 2, clamped LOD, 0, 1)`. Both paths also undergo the +strict CPU-reference check. For driver comparisons, the `release` preset +runs the same fixtures. ```powershell cmake --build --preset dev --target offscreen_check diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 82aa4b527..4fdb64dbc 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -59,11 +59,11 @@ struct PixelMismatch : std::runtime_error { }; void check_translated_pixel(ID3D12Device* device, const char* path, bool swapRB, const char* reference = nullptr, - UINT8 writeMask = D3D12_COLOR_WRITE_ENABLE_ALL); + UINT8 writeMask = D3D12_COLOR_WRITE_ENABLE_ALL, const char* rawReadback = nullptr); void check_attribute_pixel(ID3D12Device* device, const char* shader, const char* reference, bool rg); void check_compute_to_pixel(ID3D12Device* device, const char* compute, const char* pixel, const char* reference, const char* previous); -void check_pixel_quad_lod(ID3D12Device* device, const char* shader); +void check_pixel_quad_lod(ID3D12Device* device, const char* shader, const char* rawReadback = nullptr); void check_pixel_mip_clamp(ID3D12Device* device, const char* shader, unsigned expectedLevel); void check_pixel_mip_blend(ID3D12Device* device, const char* shader, float clamp, float tolerance); void check_pixel_compare(ID3D12Device* device, const char* shader, const char* reference); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 037d119a7..cac5ab66c 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -713,7 +713,8 @@ OperationResult run_check_pixel_compare(const OperationContext& ctx) OperationResult run_check_pixel_case(const OperationContext& ctx) { - check_translated_pixel(ctx.device, ctx.argv[3], false, ctx.argv[4]); + check_translated_pixel(ctx.device, ctx.argv[3], false, ctx.argv[4], D3D12_COLOR_WRITE_ENABLE_ALL, + ctx.argc == 6 ? ctx.argv[5] : nullptr); return {OutcomeKind::pass, nullptr}; } @@ -744,7 +745,7 @@ OperationResult run_check_pixel_attribute_rg(const OperationContext& ctx) OperationResult run_check_pixel_quad_lod(const OperationContext& ctx) { - check_pixel_quad_lod(ctx.device, ctx.argv[3]); + check_pixel_quad_lod(ctx.device, ctx.argv[3], ctx.argc == 5 ? ctx.argv[4] : nullptr); return {OutcomeKind::pass, nullptr}; } @@ -1254,12 +1255,12 @@ const OperationSpec kOperations[] = { {"--dual-pixel-swapped", 5, 5, nullptr, kNoGate, run_dual_pixel_swapped}, {"--sampled-coverage", 5, 5, nullptr, kNoGate, run_sampled_coverage}, {"--check-pixel-compare", 5, 5, nullptr, kNoGate, run_check_pixel_compare}, - {"--check-pixel-case", 5, 5, nullptr, kNoGate, run_check_pixel_case}, + {"--check-pixel-case", 5, 6, nullptr, kNoGate, run_check_pixel_case}, {"--check-pixel-case-rg", 5, 5, nullptr, kNoGate, run_check_pixel_case_rg}, {"--compute-to-pixel", 6, 7, nullptr, kNoGate, run_compute_to_pixel}, {"--check-pixel-attribute", 5, 5, nullptr, kNoGate, run_check_pixel_attribute}, {"--check-pixel-attribute-rg", 5, 5, nullptr, kNoGate, run_check_pixel_attribute_rg}, - {"--check-pixel-quad-lod", 4, 4, nullptr, kNoGate, run_check_pixel_quad_lod}, + {"--check-pixel-quad-lod", 4, 5, nullptr, kNoGate, run_check_pixel_quad_lod}, {"--spirv-minlod-quad-lod", 4, 4, nullptr, kGateSm60MinLodSmoke, run_check_pixel_quad_lod}, // Keep the fractional point-filter fixture on its existing gate (#809). {"--check-pixel-mip-clamp", 5, 5, nullptr, kGateSm66MinLod, run_check_pixel_mip_clamp}, diff --git a/tests/pixel_aot_render.cpp b/tests/pixel_aot_render.cpp index a92db123a..39d3aa034 100644 --- a/tests/pixel_aot_render.cpp +++ b/tests/pixel_aot_render.cpp @@ -157,7 +157,7 @@ struct Extent { void draw_verified(ID3D12Device* device, const char* path, const std::vector& levels, Extent base, UINT firstResident, const std::vector& draws, const char* capture, - ID3D12Resource* gpuConstants = nullptr) + ID3D12Resource* gpuConstants = nullptr, const char* rawReadback = nullptr) { const auto& input = levels.front(); ComPtr uploadedConstants; @@ -424,6 +424,15 @@ void draw_verified(ID3D12Device* device, const char* path, const std::vector(row), width * sizeof(Color)); + } + output.close(); + if (!output) throw std::runtime_error("Cannot save raw pixel readback"); + } float maxError = 0; std::array firstBits{}; std::vector image; @@ -528,11 +537,11 @@ void draw_verified(ID3D12Device* device, const char* path, const std::vector& levels, UINT firstResident, UINT sampledLevel, const char* capture, - ID3D12Resource* gpuConstants = nullptr) + ID3D12Resource* gpuConstants = nullptr, const char* rawReadback = nullptr) { const auto& top = levels.front(); draw_verified(device, path, levels, {top.width << firstResident, top.height << firstResident}, - firstResident, {{sampledLevel, levels.at(sampledLevel).scale}}, capture, gpuConstants); + firstResident, {{sampledLevel, levels.at(sampledLevel).scale}}, capture, gpuConstants, rawReadback); } ComPtr produce_pixel_constants(ID3D12Device* device, const char* path) @@ -574,7 +583,7 @@ ComPtr produce_pixel_constants(ID3D12Device* device, const char* } static void check_pixel(ID3D12Device* device, const char* path, bool swapRB, const char* reference, - UINT8 writeMask, ID3D12Resource* gpuConstants) + UINT8 writeMask, ID3D12Resource* gpuConstants, const char* rawReadback = nullptr) { PixelInput input{8, 8, 8, DXGI_FORMAT_R8G8B8A8_UNORM}; input.writeMask = writeMask; @@ -635,12 +644,13 @@ static void check_pixel(ID3D12Device* device, const char* path, bool swapRB, con } std::vector levels; levels.push_back(std::move(input)); - draw_verified(device, path, levels, 0, 0, nullptr, gpuConstants); + draw_verified(device, path, levels, 0, 0, nullptr, gpuConstants, rawReadback); } -void check_translated_pixel(ID3D12Device* device, const char* path, bool swapRB, const char* reference, UINT8 writeMask) +void check_translated_pixel(ID3D12Device* device, const char* path, bool swapRB, const char* reference, + UINT8 writeMask, const char* rawReadback) { - check_pixel(device, path, swapRB, reference, writeMask, nullptr); + check_pixel(device, path, swapRB, reference, writeMask, nullptr, rawReadback); } void check_compute_to_pixel(ID3D12Device* device, const char* compute, const char* pixel, @@ -652,7 +662,7 @@ void check_compute_to_pixel(ID3D12Device* device, const char* compute, const cha stale ? stale.Get() : current.Get()); } -void check_pixel_quad_lod(ID3D12Device* device, const char* shader) +void check_pixel_quad_lod(ID3D12Device* device, const char* shader, const char* rawReadback) { PixelInput top{8, 8, 1, DXGI_FORMAT_R8G8B8A8_UNORM}; PixelInput next{4, 4, 1, DXGI_FORMAT_R8G8B8A8_UNORM}; @@ -669,7 +679,8 @@ void check_pixel_quad_lod(ID3D12Device* device, const char* shader) next.rows.insert(next.rows.end(), {0, 255, 0, 255}); MipDraw draw{0, 1}; draw.partialQuad = true; - draw_verified(device, shader, {std::move(top), std::move(next)}, {8, 8}, 0, {draw}, nullptr); + draw_verified(device, shader, {std::move(top), std::move(next)}, {8, 8}, 0, {draw}, nullptr, + nullptr, rawReadback); } namespace { diff --git a/tests/pixel_get_lod_check.py b/tests/pixel_get_lod_check.py index b9fb0e51f..eb0bc587b 100644 --- a/tests/pixel_get_lod_check.py +++ b/tests/pixel_get_lod_check.py @@ -1,4 +1,5 @@ """Check both gfx1030 image_get_lod results against a CPU footprint model.""" +import hashlib import math import os from pathlib import Path @@ -67,48 +68,117 @@ def binary(directory, assembler, objcopy, library): return 0 +def compare_draws(renderer, backend, mode, operands, shaders, directory, label): + draws = [] + for name, shader in shaders: + path = directory / f"{label}-{name}.rgba32f" + print(f"{label} path={name}", flush=True) + result = subprocess.run([renderer, backend, mode, shader, *operands, path], + capture_output=True, text=True) + print(result.stdout, end="", flush=True) + if result.returncode: + print(result.stderr, end="", flush=True) + data = path.read_bytes() if path.is_file() else None + if data is not None: + assert len(data) == 8 * 8 * 16, len(data) + first = struct.unpack_from("<4f", data) + bits = struct.unpack_from("<4I", data) + print(f"first_pixel_rgba={first} bits={','.join(f'{word:08x}' for word in bits)} " + f"readback_sha256={hashlib.sha256(data).hexdigest()}", flush=True) + draws.append((result.returncode, data)) + + (translated_code, translated), (direct_code, direct) = draws + if translated is not None and direct is not None: + if translated == direct: + print(f"{label} translated/direct readbacks identical (256 FP32 channels)", flush=True) + else: + for index, (left, right) in enumerate(zip(struct.iter_unpack(" image : register(t0); +SamplerState pointClamp : register(s0); +cbuffer Footprint : register(b0) { + float4 scales; +}; + +float4 lower_scale(float2 uv : TEXCOORD0) : SV_Target0 { + float2 coord = uv * scales.zw; + float clamped = image.CalculateLevelOfDetail(pointClamp, coord); + float raw = image.CalculateLevelOfDetailUnclamped(pointClamp, coord); + return float4(clamped, raw, 0.5, 1.0); +} + +float4 upper_clamp(float2 uv : TEXCOORD0) : SV_Target0 { + float2 coord = float2(uv.x * scales.z, uv.y); + float clamped = image.CalculateLevelOfDetail(pointClamp, coord); + float raw = image.CalculateLevelOfDetailUnclamped(pointClamp, coord); + return float4(raw - 2.0, clamped, 0.0, 1.0); +} From 41c6e60335a343a6f6fa631be98814c3d9b4e35f Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:09:11 +0100 Subject: [PATCH 081/775] tests/startup_stream_depth: depth-only PSO uses a pixel shader that exports nothing (no SV_Target0) --- tests/startup_stream_depth.cpp | 24 ++++++++++++------------ tests/startup_stream_depth_check.py | 7 ++++--- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/tests/startup_stream_depth.cpp b/tests/startup_stream_depth.cpp index b7c42f562..c2be34807 100644 --- a/tests/startup_stream_depth.cpp +++ b/tests/startup_stream_depth.cpp @@ -177,10 +177,10 @@ int execute_guest_list(void* queue, void* list, void* fence, UINT64 fence_value) int main(int argc, char** argv) { - if (argc != 7 && argc != 14) return 2; - std::vector vs_front, vs_back, ps_green, ps_red; + if (argc != 8 && argc != 15) return 2; + std::vector vs_front, vs_back, ps_green, ps_red, ps_empty; if (!read_bytes(argv[1], vs_front) || !read_bytes(argv[2], vs_back) || - !read_bytes(argv[3], ps_green) || !read_bytes(argv[4], ps_red)) return 3; + !read_bytes(argv[3], ps_green) || !read_bytes(argv[4], ps_red) || !read_bytes(argv[7], ps_empty)) return 3; const bool hardware = std::strcmp(argv[6], "hardware") == 0; ComPtr adapter; @@ -221,8 +221,8 @@ int main(int argc, char** argv) void* pso_back_less = create_stream_pso(guest, root, vs_back, ps_red, ds_less, false); void* pso_front_off = create_stream_pso(guest, root, vs_front, ps_green, ds_disabled, false); void* pso_back_off = create_stream_pso(guest, root, vs_back, ps_red, ds_disabled, false); - // Depth-only pass: no pixel shader, so nothing declares SV_Target0 for a zero-RTV bind. - void* pso_front_depth_only = create_stream_pso(guest, root, vs_front, {}, ds_less, true); + // Depth-only pass: the pixel shader exports nothing, so nothing declares SV_Target0 for a zero-RTV bind. + void* pso_front_depth_only = create_stream_pso(guest, root, vs_front, ps_empty, ds_less, true); // DepthBoundsTestEnable has no translated equivalent: the pipeline is refused for drawing, not translated without it. void* pso_front_bounds = create_stream_pso(guest, root, vs_front, ps_green, ds_less, true, TRUE); if (!pso_front_bounds || !pso_front_less || !pso_back_less || !pso_front_off || !pso_back_off || !pso_front_depth_only) return 9; @@ -314,13 +314,13 @@ int main(int argc, char** argv) return read_stream_target(desktop.Get(), state, out_path); }; - if (const int rc = run_case(1, argv[7], Bind::normal, pso_front_less, pso_back_less)) return rc; - if (const int rc = run_case(2, argv[8], Bind::normal, pso_front_off, pso_back_off)) return rc; - if (const int rc = run_case(3, argv[9], Bind::depth_only, pso_front_depth_only, pso_back_less)) return rc; - if (const int rc = run_case(4, argv[10], Bind::read_only_depth, pso_front_less, pso_back_less)) return rc; + if (const int rc = run_case(1, argv[8], Bind::normal, pso_front_less, pso_back_less)) return rc; + if (const int rc = run_case(2, argv[9], Bind::normal, pso_front_off, pso_back_off)) return rc; + if (const int rc = run_case(3, argv[10], Bind::depth_only, pso_front_depth_only, pso_back_less)) return rc; + if (const int rc = run_case(4, argv[11], Bind::read_only_depth, pso_front_less, pso_back_less)) return rc; // Controls: nothing may be drawn for a wrong descriptor kind or an enabled depth bounds test. - if (const int rc = run_case(5, argv[11], Bind::rtv_as_depth, pso_front_less, pso_back_less)) return rc; - if (const int rc = run_case(6, argv[12], Bind::dsv_as_target, pso_front_less, pso_back_less)) return rc; - if (const int rc = run_case(7, argv[13], Bind::normal, pso_front_bounds, pso_front_bounds)) return rc; + if (const int rc = run_case(5, argv[12], Bind::rtv_as_depth, pso_front_less, pso_back_less)) return rc; + if (const int rc = run_case(6, argv[13], Bind::dsv_as_target, pso_front_less, pso_back_less)) return rc; + if (const int rc = run_case(7, argv[14], Bind::normal, pso_front_bounds, pso_front_bounds)) return rc; return 0; } diff --git a/tests/startup_stream_depth_check.py b/tests/startup_stream_depth_check.py index e02e1609f..a60454eb5 100644 --- a/tests/startup_stream_depth_check.py +++ b/tests/startup_stream_depth_check.py @@ -21,8 +21,8 @@ def vertex(z_bits): def check(directory, consumer, backend): cache = directory / "cache" cache.mkdir() - vs_front, vs_back, ps_green, ps_red, root = ( - directory / name for name in ("vs_front", "vs_back", "ps_green", "ps_red", "root") + vs_front, vs_back, ps_green, ps_red, root, ps_empty = ( + directory / name for name in ("vs_front", "vs_back", "ps_green", "ps_red", "root", "ps_empty") ) out_pos, out_neg, out_depthonly, out_readonly, out_rtv_depth, out_dsv_target, out_bounds = ( directory / name for name in ("pixels_pos", "pixels_neg", "pixels_depthonly", "pixels_readonly", @@ -32,10 +32,11 @@ def check(directory, consumer, backend): vs_back.write_bytes(vertex(0x3f400000)) # z = 0.75f ps_green.write_bytes(pixel(True)) ps_red.write_bytes(pixel(False)) + ps_empty.write_bytes(container(0, [0xbf810000])) # exports nothing: the depth-only pass declares no SV_Target0 env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_D3D12_DEBUG="1", X2W_SHADER_CACHE=str(cache)) - base_args = [consumer, str(vs_front), str(vs_back), str(ps_green), str(ps_red), str(root), backend] + base_args = [consumer, str(vs_front), str(vs_back), str(ps_green), str(ps_red), str(root), backend, str(ps_empty)] req = subprocess.run(base_args, env=env, capture_output=True, text=True) if backend == "hardware" and req.returncode == 77: print("No D3D12 feature-level 12 hardware adapter") From 569b58822b14921ba3955579246444c7d6d6b66b Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:11:29 +0100 Subject: [PATCH 082/775] gfx2hlsl: translate an export-less pixel shader as a void depth-only main --- tools/startup/gfx2hlsl.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index c922e52f4..bb49db1ec 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1146,7 +1146,11 @@ def hlsl_vs(self): def hlsl_ps(self): s = self.ps targets = sorted(int(k[3:]) for k in s.exports if k.startswith('mrt')) - out = self.common() + ['struct PSIn {'] + self.interface(True) + ['};', 'struct PSOut {'] + out = self.common() + ['struct PSIn {'] + self.interface(True) + ['};'] + if not targets: # depth-only: no output struct, so the pipeline declares no SV_Target + out += ['void main(PSIn i) {'] + s.declarations() + s.body() + ['}'] + return '\n'.join(out) + '\n' + out.append('struct PSOut {') for t in targets: kind = self.mrt_kind(t) out.append(' %s mrt%d : SV_Target%d;' % ({'int': 'int4', 'uint': 'uint4'}.get(kind, 'float4'), t, t)) @@ -1218,7 +1222,7 @@ def translate_to(out_dir, key, vs_code, ps_code, root_blob, check=True, rtv_form def classify(blob): text = ' '.join(x[3] for x in decode(strip_header(blob)) if x[2] == 'exp') - return 'vs' if 'pos' in text else 'ps' if 'mrt' in text else 'other' + return 'vs' if 'pos' in text else 'ps' if 'mrt' in text or not text else 'other' # no export: a depth-only pixel shader def translate_request(out_dir, key): From 7d019d80e6f08dae72d0b2010746d7140a6bfb42 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:12:17 +0100 Subject: [PATCH 083/775] Use typed element sizes for slot-70 buffer SRVs and refuse unsupported typed formats --- docs/experiments.md | 12 ++++++++---- docs/startup-runtime.md | 6 ++++++ src/startup_stubs/d3d12_draw.inl | 6 ++++-- src/startup_stubs/memory_srv_buffer.h | 4 ---- tests/startup_memory_srv_buffer_check.cpp | 8 ++++++++ 5 files changed, 26 insertions(+), 10 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index c783e3cad..b3d35701c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9609,10 +9609,14 @@ array size, mips, layout, flags, alignment and sample count and quality; view di component mapping, with the mip, plane and array fields for 2D and 2D-array views and the first element, count, stride and flags for buffer views (any other dimension prints its six raw words); the destination handle and whether it is a descriptor of a known CBV/SRV/UAV heap; the address and -whether its first byte is readable. Only 2D textures are supported: a buffer view or an -acceleration-structure view is refused with `unsupported_description` and the line says so. No -buffer or acceleration-structure semantics are implemented; what a title expects from such a call -has not been observed in a source-built fixture. +whether its first byte is readable. Textures (2D) and buffers are supported, plus raytracing acceleration-structure views on adapters that +report raytracing support (see "Buffer and raytracing acceleration-structure memory SRVs" in +`docs/startup-runtime.md`). A buffer view must name a live placed or committed buffer, with a raw, +structured (stride up to 2048) or typed format; typed element sizes come from the format, and formats +that cannot back a typed buffer SRV (sRGB, block-compressed, depth/stencil, typeless, BGRA) are refused +with `unsupported_description`. An acceleration-structure view on an adapter without raytracing is +refused with `raytracing_unsupported`. Translated draws bind typed buffer views with the format's +element size and stride. `startup_memory_srv_report` compares the line field by field for buffer, acceleration-structure and array views and for unreadable arguments. `startup_address_srv_hardware` and diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d8e4bab45..87cf1b7d2 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -719,6 +719,12 @@ descriptions with: forwards to slot 18 with `pResource == nullptr`. Adapters without raytracing support refuse the call cleanly (`raytracing_unsupported`) without removing the device. +Typed element bytes come from the format (1 to 16 bytes). Formats that cannot back a typed buffer SRV +(sRGB, BGRA, block-compressed, depth/stencil, typeless, planar) are refused with +`unsupported_description` and leave the destination descriptor unchanged. Translated draws bind typed +views with the format's element size and stride. The refusal reasons are listed in +`docs/experiments.md` ("Name the cause of a refused slot 70 call"). + Checks: - `ctest --preset release --no-tests=error -R '^startup_memory_srv_(report|buffer)$' -V` diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 157a3a388..fb5d237d7 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -938,10 +938,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI std::memcpy(&view, record.desc, 40); Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); if (view.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && resource && resource->own().title_memory) { - const UINT element = view.Buffer.StructureByteStride ? view.Buffer.StructureByteStride : 4; + const bool typed_view = !view.Buffer.StructureByteStride && view.Format != DXGI_FORMAT_R32_TYPELESS; + const UINT element = view.Buffer.StructureByteStride ? view.Buffer.StructureByteStride + : typed_view ? x2w_startup::typed_buffer_format_bytes(view.Format) : 4; address = reinterpret_cast(resource->own().title_memory) + view.Buffer.FirstElement * element; bytes = std::size_t{view.Buffer.NumElements} * element; - strides[i] = view.Buffer.StructureByteStride; + strides[i] = typed_view ? element : view.Buffer.StructureByteStride; } } } diff --git a/src/startup_stubs/memory_srv_buffer.h b/src/startup_stubs/memory_srv_buffer.h index 70e3e193a..688bb0c71 100644 --- a/src/startup_stubs/memory_srv_buffer.h +++ b/src/startup_stubs/memory_srv_buffer.h @@ -35,13 +35,9 @@ inline std::uint32_t typed_buffer_format_bytes(DXGI_FORMAT format) case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: - case DXGI_FORMAT_B8G8R8A8_UNORM: - case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: - case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_UINT: diff --git a/tests/startup_memory_srv_buffer_check.cpp b/tests/startup_memory_srv_buffer_check.cpp index 9cbbbbe90..116f08ef3 100644 --- a/tests/startup_memory_srv_buffer_check.cpp +++ b/tests/startup_memory_srv_buffer_check.cpp @@ -119,6 +119,14 @@ int main() const auto typ_ok = typed_view(DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 4); check("typed valid", x2w_startup::supports_buffer_memory_srv(buf, typ_ok)); check("typed unknown format", !x2w_startup::supports_buffer_memory_srv(buf, typed_view(DXGI_FORMAT_UNKNOWN, 0, 1))); + check("typed element bytes 16", x2w_startup::typed_buffer_format_bytes(DXGI_FORMAT_R32G32B32A32_FLOAT) == 16); + check("typed element bytes 12", x2w_startup::typed_buffer_format_bytes(DXGI_FORMAT_R32G32B32_UINT) == 12); + check("typed element bytes 2", x2w_startup::typed_buffer_format_bytes(DXGI_FORMAT_R16_UNORM) == 2); + check("typed srgb rejected", !x2w_startup::supports_buffer_memory_srv(buf, typed_view(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, 0, 1))); + check("typed bgra srgb rejected", !x2w_startup::supports_buffer_memory_srv(buf, typed_view(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, 0, 1))); + check("typed bc rejected", !x2w_startup::supports_buffer_memory_srv(buf, typed_view(DXGI_FORMAT_BC7_UNORM, 0, 1))); + check("typed depth rejected", !x2w_startup::supports_buffer_memory_srv(buf, typed_view(DXGI_FORMAT_D32_FLOAT, 0, 1))); + check("typed typeless rejected", !x2w_startup::supports_buffer_memory_srv(buf, typed_view(DXGI_FORMAT_R32G32B32A32_TYPELESS, 0, 1))); check("typed resolve interior", x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x10010, typ_ok, resolved) && resolved.Buffer.FirstElement == 2); From 06edf01ab3fc7b42b6d9d4784f76bf55127cecd3 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:12:44 +0100 Subject: [PATCH 084/775] startup_stubs: keep per-kind GameInput sequence numbers and per-kind history rings --- src/startup_stubs/gameinput.cpp | 128 +++++++++++++++++++------------ tests/startup_gameinput_keys.cpp | 32 +++++++- 2 files changed, 108 insertions(+), 52 deletions(-) diff --git a/src/startup_stubs/gameinput.cpp b/src/startup_stubs/gameinput.cpp index f474cc133..b7294046f 100644 --- a/src/startup_stubs/gameinput.cpp +++ b/src/startup_stubs/gameinput.cpp @@ -277,22 +277,34 @@ struct Reading : Object { GamepadState state; std::uint32_t key_count; KeyState keys[max_keys]; - u64 sequence, timestamp; + u64 timestamp; + u64 pad_sequence, key_sequence; // per-kind sequence numbers, as GameInput documents them }; constexpr std::uint32_t history_pad = 1, history_keys = 2; struct HistoryEntry { - u64 sequence, timestamp; + u64 order; // internal ordering across kinds; never exposed to the title + u64 pad_sequence, key_sequence; + u64 timestamp; GamepadState pad; std::uint32_t key_count; KeyState keys[max_keys]; - std::uint32_t changed; // history_pad / history_keys: which device's state differs from the previous entry +}; +// One retention ring per kind, indexed by that kind's own sequence: keyboard traffic never evicts gamepad history. +struct KindRing { + HistoryEntry entries[history_capacity]; + u64 latest; // latest sequence of this kind (0 = none yet) + std::size_t count; }; Table<32> reading_table; -volatile LONG64 sequence_counter; -HistoryEntry history_ring[history_capacity]; -std::size_t history_count; +KindRing pad_ring, key_ring; +u64 order_counter; +HistoryEntry latest_entry; SRWLOCK state_lock = SRWLOCK_INIT; +bool wants_gamepad(std::uint32_t kind) { return (kind & (kind_gamepad | kind_controller_bits)) != 0; } +bool wants_keyboard(std::uint32_t kind) { return (kind & kind_keyboard) != 0; } +bool wants_any(std::uint32_t kind) { return wants_gamepad(kind) || wants_keyboard(kind); } + u64 __stdcall reading_release(Reading* self) { const LONG left = InterlockedDecrement(&self->refs); @@ -300,7 +312,12 @@ u64 __stdcall reading_release(Reading* self) return static_cast(left); } std::uint32_t __stdcall reading_kind(Reading* self) { return self->kind; } -u64 __stdcall reading_sequence(Reading* self, std::uint32_t) { return self->sequence; } +u64 __stdcall reading_sequence(Reading* self, std::uint32_t kind) +{ + if ((kind & kind_keyboard) && (self->kind & kind_keyboard)) return self->key_sequence; + if (wants_gamepad(kind) && wants_gamepad(self->kind)) return self->pad_sequence; + return 0; +} u64 __stdcall reading_timestamp(Reading* self) { return self->timestamp; } void __stdcall reading_device(Reading* self, Object** device) { @@ -347,9 +364,6 @@ bool __stdcall reading_gamepad(Reading* self, GamepadState* out) return true; } -bool wants_gamepad(std::uint32_t kind) { return (kind & (kind_gamepad | kind_controller_bits)) != 0; } -bool wants_keyboard(std::uint32_t kind) { return (kind & kind_keyboard) != 0; } -bool wants_any(std::uint32_t kind) { return wants_gamepad(kind) || wants_keyboard(kind); } std::uint32_t resolve_reading_kind(std::uint32_t requested, Object* device) { @@ -368,59 +382,73 @@ HistoryEntry capture_current() const std::uint32_t key_count = sample_keys(keys, max_keys); AcquireSRWLockExclusive(&state_lock); - std::uint32_t changed = (history_count == 0) ? (history_pad | history_keys) : 0; + std::uint32_t changed = (order_counter == 0) ? (history_pad | history_keys) : 0; if (!changed) { - const HistoryEntry& latest = history_ring[static_cast(sequence_counter) % history_capacity]; - if (std::memcmp(&pad, &latest.pad, sizeof(pad)) != 0) changed |= history_pad; - if (key_count != latest.key_count || - (key_count > 0 && std::memcmp(keys, latest.keys, key_count * sizeof(KeyState)) != 0)) + if (std::memcmp(&pad, &latest_entry.pad, sizeof(pad)) != 0) changed |= history_pad; + if (key_count != latest_entry.key_count || + (key_count > 0 && std::memcmp(keys, latest_entry.keys, key_count * sizeof(KeyState)) != 0)) changed |= history_keys; } if (changed) { - ++sequence_counter; - HistoryEntry& slot = history_ring[static_cast(sequence_counter) % history_capacity]; - slot.sequence = static_cast(sequence_counter); - slot.timestamp = now_microseconds(); - slot.pad = pad; - slot.changed = changed; - slot.key_count = key_count; - if (key_count > 0) std::memcpy(slot.keys, keys, key_count * sizeof(KeyState)); - if (history_count < history_capacity) ++history_count; + latest_entry.order = ++order_counter; + latest_entry.timestamp = now_microseconds(); + latest_entry.pad = pad; + latest_entry.key_count = key_count; + if (key_count > 0) std::memcpy(latest_entry.keys, keys, key_count * sizeof(KeyState)); + if (changed & history_pad) latest_entry.pad_sequence = ++pad_ring.latest; + if (changed & history_keys) latest_entry.key_sequence = ++key_ring.latest; + if (changed & history_pad) { + pad_ring.entries[pad_ring.latest % history_capacity] = latest_entry; + if (pad_ring.count < history_capacity) ++pad_ring.count; + } + if (changed & history_keys) { + key_ring.entries[key_ring.latest % history_capacity] = latest_entry; + if (key_ring.count < history_capacity) ++key_ring.count; + } } - const HistoryEntry result = history_ring[static_cast(sequence_counter) % history_capacity]; + const HistoryEntry result = latest_entry; ReleaseSRWLockExclusive(&state_lock); return result; } std::uint32_t history_mask(std::uint32_t reading_kind) { - return ((reading_kind & kind_gamepad) ? history_pad : 0) | ((reading_kind & kind_keyboard) ? history_keys : 0); + return (wants_gamepad(reading_kind) ? history_pad : 0) | ((reading_kind & kind_keyboard) ? history_keys : 0); +} + +// Looks `step` (+1 / -1) kinds-sequence away from `ref_sequence` in one kind's ring. +// Returns 0 on hit, -1 if there is none (not found), -2 if the wanted entry was already evicted (too old). +int find_in_ring(const KindRing& ring, u64 ref_sequence, int step, HistoryEntry& out) +{ + if (ring.count == 0) return -1; + const u64 target = step > 0 ? ref_sequence + 1 : ref_sequence - 1; + if (target == 0 || target > ring.latest) return -1; + if (target < ring.latest - ring.count + 1) return -2; + out = ring.entries[target % history_capacity]; + return 0; } -// Walks the history from `start` in `step` (+1 / -1) to the nearest entry that changed the wanted device(s). -// Returns 0 on hit, -1 if there is none (not found), -2 if the walk ran past the evicted end (too old). -int find_history(u64 start, int step, std::uint32_t mask, HistoryEntry& out) +// Nearest entry in `step` direction that changed any wanted kind; ordering across kinds uses the internal order. +int find_history(const Reading& ref, int step, std::uint32_t mask, HistoryEntry& out) { AcquireSRWLockShared(&state_lock); int result = -1; - const u64 latest = static_cast(sequence_counter); - if (history_count != 0 && start != 0 && start <= latest) { - const u64 oldest = latest - history_count + 1; - if (start < oldest) { + bool have = false; + for (int i = 0; i < 2; ++i) { + const std::uint32_t bit = i == 0 ? history_pad : history_keys; + if (!(mask & bit)) continue; + const KindRing& ring = i == 0 ? pad_ring : key_ring; + HistoryEntry candidate{}; + const int found = find_in_ring(ring, i == 0 ? ref.pad_sequence : ref.key_sequence, step, candidate); + if (found == -2) { result = -2; - } else { - for (u64 seq = start; seq >= oldest && seq <= latest; seq += static_cast(static_cast(step))) { - const HistoryEntry& entry = history_ring[seq % history_capacity]; - if (entry.changed & mask) { - out = entry; - result = 0; - break; - } - if (step < 0 && seq == oldest) { - result = oldest > 1 ? -2 : -1; - break; - } - } + have = false; + break; + } + if (found == 0 && (!have || (step > 0 ? candidate.order < out.order : candidate.order > out.order))) { + out = candidate; + have = true; + result = 0; } } ReleaseSRWLockShared(&state_lock); @@ -436,7 +464,8 @@ Reading* make_reading(const HistoryEntry& entry, std::uint32_t kind, Object* dev reading->state = entry.pad; reading->key_count = entry.key_count; if (entry.key_count > 0) std::memcpy(reading->keys, entry.keys, entry.key_count * sizeof(KeyState)); - reading->sequence = entry.sequence; + reading->pad_sequence = entry.pad_sequence; + reading->key_sequence = entry.key_sequence; reading->timestamp = entry.timestamp; return reading; } @@ -479,7 +508,7 @@ HRESULT __stdcall input_next_reading(Object*, Reading* reference, std::uint32_t if (FAILED(check_hr)) return check_hr; capture_current(); HistoryEntry entry{}; - const int found = find_history(reference->sequence + 1, 1, history_mask(resolve_reading_kind(kind, device)), entry); + const int found = find_history(*reference, 1, history_mask(resolve_reading_kind(kind, device)), entry); if (found == -2) return reading_too_old; if (found != 0) return reading_not_found; *out = make_reading(entry, kind, device); @@ -494,9 +523,8 @@ HRESULT __stdcall input_previous_reading(Object*, Reading* reference, std::uint3 if (!reference) return E_INVALIDARG; const HRESULT check_hr = validate_kind_and_device(kind, device); if (FAILED(check_hr)) return check_hr; - if (reference->sequence <= 1) return reading_not_found; HistoryEntry entry{}; - const int found = find_history(reference->sequence - 1, -1, history_mask(resolve_reading_kind(kind, device)), entry); + const int found = find_history(*reference, -1, history_mask(resolve_reading_kind(kind, device)), entry); if (found == -2) return reading_too_old; if (found != 0) return reading_not_found; *out = make_reading(entry, kind, device); diff --git a/tests/startup_gameinput_keys.cpp b/tests/startup_gameinput_keys.cpp index 6b9cfdfbf..6c065177b 100644 --- a/tests/startup_gameinput_keys.cpp +++ b/tests/startup_gameinput_keys.cpp @@ -334,11 +334,38 @@ int main(int argc, char** argv) const std::uint64_t base = pad_a ? pad_a->GetSequenceNumber(kind_gamepad) : 0; SetEnvironmentVariableA("X2W_INPUT_KEYS", "51"); input->GetCurrentReading(kind_keyboard, kbd_device, &tmp); + const std::uint64_t key51 = tmp ? tmp->GetSequenceNumber(kind_keyboard) : 0; if (tmp) tmp->Release(); SetEnvironmentVariableA("X2W_INPUT_KEYS", "52"); input->GetCurrentReading(kind_keyboard, kbd_device, &tmp); if (tmp) tmp->Release(); tmp = nullptr; + // Control: repeated keyboard-only reads never move the gamepad kind's sequence number. + for (int i = 0; i < 3; ++i) { + SetEnvironmentVariableA("X2W_INPUT_KEYS", i % 2 ? "53" : "54"); + input->GetCurrentReading(kind_keyboard, kbd_device, &tmp); + if (tmp) tmp->Release(); + tmp = nullptr; + } + SetEnvironmentVariableA("X2W_INPUT_KEYS", "52"); + IGameInputReading* pad_same = nullptr; + failures += check(input->GetCurrentReading(kind_gamepad, pad_device, &pad_same) == S_OK && pad_same && + pad_same->GetSequenceNumber(kind_gamepad) == base, + "gamepad sequence is unchanged after repeated keyboard-only reads"); + if (pad_same) pad_same->Release(); + // Control: keyboard-only traffic beyond the ring size must not age out the gamepad reference. + for (int i = 0; i < 100; ++i) { + char keys[8]; + std::snprintf(keys, sizeof keys, "%X", 0x30 + i % 2); + SetEnvironmentVariableA("X2W_INPUT_KEYS", keys); + input->GetCurrentReading(kind_keyboard, kbd_device, &tmp); + if (tmp) tmp->Release(); + tmp = nullptr; + } + SetEnvironmentVariableA("X2W_INPUT_KEYS", "52"); + input->GetCurrentReading(kind_keyboard, kbd_device, &tmp); + if (tmp) tmp->Release(); + tmp = nullptr; failures += check(input->GetNextReading(pad_a, kind_gamepad, pad_device, &tmp) == reading_not_found && tmp == nullptr, "keyboard-only changes must not be a next gamepad reading"); pad_words[1] = 4; // buttons: A @@ -347,7 +374,7 @@ int main(int argc, char** argv) if (pad_b) { GamepadState gs{}; failures += check(pad_b->GetGamepadState(&gs) && gs.buttons == 4, "next gamepad reading carries the new buttons"); - failures += check(pad_b->GetSequenceNumber(kind_gamepad) == base + 3, "next gamepad reading skips keyboard-only entries"); + failures += check(pad_b->GetSequenceNumber(kind_gamepad) == base + 1, "next gamepad reading carries the next gamepad sequence"); IGameInputReading* back = nullptr; failures += check(input->GetPreviousReading(pad_b, kind_gamepad, pad_device, &back) == S_OK && back, "previous gamepad reading"); if (back) { @@ -357,7 +384,8 @@ int main(int argc, char** argv) IGameInputReading* kback = nullptr; failures += check(input->GetPreviousReading(pad_b, kind_keyboard, kbd_device, &kback) == S_OK && kback, "previous keyboard reading"); if (kback) { - failures += check(kback->GetSequenceNumber(kind_keyboard) == base + 2, "previous keyboard reading skips pad-only entries"); + failures += check(kback->GetSequenceNumber(kind_keyboard) < pad_b->GetSequenceNumber(kind_keyboard) && + kback->GetSequenceNumber(kind_keyboard) > key51, "previous keyboard reading skips pad-only entries"); kback->Release(); } pad_b->Release(); From addc99c2667377db8eba9fd54a66aeefe476a7c0 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:12:44 +0100 Subject: [PATCH 085/775] tests/startup_stream_depth: request run ends after pipeline creation with the extra shader argument --- tests/startup_stream_depth.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/startup_stream_depth.cpp b/tests/startup_stream_depth.cpp index c2be34807..6d58f46d4 100644 --- a/tests/startup_stream_depth.cpp +++ b/tests/startup_stream_depth.cpp @@ -226,7 +226,7 @@ int main(int argc, char** argv) // DepthBoundsTestEnable has no translated equivalent: the pipeline is refused for drawing, not translated without it. void* pso_front_bounds = create_stream_pso(guest, root, vs_front, ps_green, ds_less, true, TRUE); if (!pso_front_bounds || !pso_front_less || !pso_back_less || !pso_front_off || !pso_back_off || !pso_front_depth_only) return 9; - if (argc == 7) return 0; + if (argc == 8) return 0; ComPtr desktop; if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; From d2c8c504be279c24697cb44f30bdae96a709c1ae Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 11:53:39 +0100 Subject: [PATCH 086/775] runtime: fail a DirectStorage request on allocation failure without extra stack work The queue worker already caught std::exception, but formatted and logged the failure inside the handler, on a stack that grows on demand. It now only records a reason in a fixed buffer inside the handler, logs after the handler has left, also fails the request on a non-standard exception, and runs on a thread whose stack is committed at creation. startup_storage_alloc_failure puts the process under a job commit limit, submits a request that needs more, and checks that it fails, that the worker survives and that the next request returns correct data. --- CMakeLists.txt | 8 + docs/startup-runtime.md | 15 ++ src/startup_stubs/xcrdapi.cpp | 103 +++++++++---- tests/startup_storage_alloc_failure.cpp | 185 ++++++++++++++++++++++++ 4 files changed, 280 insertions(+), 31 deletions(-) create mode 100644 tests/startup_storage_alloc_failure.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 571cfb8a0..6828be35d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -338,6 +338,14 @@ add_executable(startup_inflate_status tests/startup_inflate_status.cpp) target_compile_features(startup_inflate_status PRIVATE cxx_std_17) target_include_directories(startup_inflate_status PRIVATE src) add_test(NAME startup_inflate_status COMMAND startup_inflate_status) +# An allocation failure on the DirectStorage stand-in's worker fails that request, and the worker +# serves the next one (#1199). Skips (77) where the system does not enforce a job commit limit. +add_executable(startup_storage_alloc_failure tests/startup_storage_alloc_failure.cpp) +target_compile_features(startup_storage_alloc_failure PRIVATE cxx_std_17) +target_link_libraries(startup_storage_alloc_failure PRIVATE psapi) +add_dependencies(startup_storage_alloc_failure startup_stub_xcrdapi) +add_test(NAME startup_storage_alloc_failure COMMAND startup_storage_alloc_failure "$") +set_tests_properties(startup_storage_alloc_failure PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) target_compile_features(startup_stub_consumer PRIVATE cxx_std_17) target_link_libraries(startup_stub_consumer PRIVATE startup_stub_chad startup_stub_xg_xs xmem_shim d3d12_xs_shim) # APU heap stand-in: ApuFree reuse, coalescing, refused requests and concurrent callers (docs/startup-runtime.md). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 1974b3d2c..43519bf3b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -397,6 +397,21 @@ These are measured on one executable; treat them as hypotheses for others. entire page detects the wrong stream. Moving the second request by the same distance reaches EOF and leaves the destination untouched. A subsequent request using its directory offset succeeds. Reproduce with `ctest --preset release --no-tests=error -R '^startup_storage_directory_batch$' -V`. +- **DirectStorage allocation failure (#1199, item 3).** A queue worker runs each entry inside + a handler that turns any exception, including `std::bad_alloc` from a buffer sized by a request + field, into a failed request: the next status entry reports `E_FAIL`, the destination is + untouched and the worker serves the following entries. The handler only copies a short reason + into a fixed buffer; the log line is written after the handler has left and after the request's + buffers were freed, so no formatting or allocation runs while the exception is in flight. The + worker is a `CreateThread` thread whose stack is committed at creation (1 MiB, `worker_stack_commit`) + instead of growing on demand, because when the system is out of commit an untouched stack page + cannot be committed either. The original `0xc00000fd` (stack overflow) was not reproduced here, + and the stack-commit cause is a hypothesis from reading the code, not a measurement. The + `startup_storage_alloc_failure` check puts its own process under a job commit limit, submits + a request that declares a 1.5 GiB inflated size, expects a failure status within a timeout and + then a correct result for a normal request on the same queue. It returns 77 where the limit is + not enforced. + Reproduce with `ctest --preset release --no-tests=error -R '^startup_storage_alloc_failure$' -V`. ## Shortcuts that are known to be wrong diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 716d9e810..f4e8e5f21 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include @@ -599,42 +599,83 @@ void run_entry(Object* self, Entry& entry) } } +// Stack committed up front for a queue worker. The thread decodes request buffers sized from request +// fields, and when one allocation fails it also runs the exception unwinder and the failure log. Once +// the system is out of commit a stack page that was never touched cannot be committed either, so the +// stack is committed at creation (CreateThread without STACK_SIZE_PARAMS_ARE_A_RESERVATION treats the +// size as the committed size; the reserved size stays the image default or larger). +constexpr SIZE_T worker_stack_commit = 1u << 20; + +// Failure text is held in caller-provided storage: nothing here allocates. +void copy_reason(char (&reason)[96], const char* text) noexcept +{ + std::size_t i = 0; + for (; text && text[i] && i + 1 < sizeof reason; ++i) reason[i] = text[i]; + reason[i] = 0; +} + +// Fails the entry that threw: the next status entry reports E_FAIL, the worker goes on with the queue. +void fail_entry(Object* self, const Entry& entry, const char* reason) noexcept +{ + InterlockedIncrement(&requests_failed); + InterlockedExchange(&self->pending, static_cast(E_FAIL)); + static LONG reported; + if (InterlockedIncrement(&reported) <= 12) + log("x2w-dstorage entry type %d failed: %s (options=0x%llx)", static_cast(entry.type), reason, + entry.type == Entry::request ? *reinterpret_cast(entry.bytes) : 0ull); +} + +DWORD WINAPI queue_worker(void* parameter) +{ + auto* const self = static_cast(parameter); + QueueWork& work = *self->work; + for (;;) { + Entry entry; + { + std::unique_lock lock(work.mutex); + work.wake.wait(lock, [&] { return !work.submitted.empty(); }); + entry = std::move(work.submitted.front()); + work.submitted.pop_front(); + } + // Buffers are sized from request fields; a failed allocation fails that request instead of + // ending the process (an exception leaving a thread calls terminate). The handlers only note + // the reason in a fixed buffer: the request's buffers are already freed when a handler runs, + // and the log is written after the handler has left, so no formatting runs while the + // exception is in flight on this stack. + char reason[96] = ""; + bool failed = false; + try { + run_entry(self, entry); + } catch (const std::bad_alloc&) { + failed = true; + copy_reason(reason, "out of memory"); + } catch (const std::exception& error) { + failed = true; + copy_reason(reason, error.what()); + } catch (...) { + failed = true; + copy_reason(reason, "unknown exception"); + } + if (failed) fail_entry(self, entry, reason); + { + const std::lock_guard guard(work.mutex); + if (work.submitted.empty()) { + work.cached_streams.clear(); + } + } + } +} + QueueWork& work_of(Object* self) { static std::mutex create; const std::lock_guard guard(create); if (!self->work) { self->work = new QueueWork; - std::thread([self] { - QueueWork& work = *self->work; - for (;;) { - Entry entry; - { - std::unique_lock lock(work.mutex); - work.wake.wait(lock, [&] { return !work.submitted.empty(); }); - entry = std::move(work.submitted.front()); - work.submitted.pop_front(); - } - // Buffers are sized from request fields; a failed allocation fails that request - // instead of ending the process (an exception leaving a thread calls terminate). - try { - run_entry(self, entry); - } catch (const std::exception& error) { - InterlockedIncrement(&requests_failed); - InterlockedExchange(&self->pending, static_cast(E_FAIL)); - static LONG reported; - if (InterlockedIncrement(&reported) <= 12) - log("x2w-dstorage entry type %d failed: %s (options=0x%llx)", static_cast(entry.type), error.what(), - entry.type == Entry::request ? *reinterpret_cast(entry.bytes) : 0ull); - } - { - const std::lock_guard guard(work.mutex); - if (work.submitted.empty()) { - work.cached_streams.clear(); - } - } - } - }).detach(); + HANDLE worker = CreateThread(nullptr, worker_stack_commit, queue_worker, self, 0, nullptr); + if (!worker) worker = CreateThread(nullptr, 0, queue_worker, self, 0, nullptr); + if (worker) CloseHandle(worker); + else log("x2w-dstorage queue worker not started: error %lu", GetLastError()); } return *self->work; } diff --git a/tests/startup_storage_alloc_failure.cpp b/tests/startup_storage_alloc_failure.cpp new file mode 100644 index 000000000..b60119873 --- /dev/null +++ b/tests/startup_storage_alloc_failure.cpp @@ -0,0 +1,185 @@ +// An allocation failure on the DirectStorage stand-in's queue worker fails that request and leaves +// the worker running (#1199, item 3). +// +// Request buffers are sized from request fields. The failure here is a real one, the same kind a +// job-wide commit cap causes in a startup run: this process joins a job object whose process-memory +// limit is a little above its current commit, then submits a zlib request whose declared inflated +// size is far above the limit. The stand-in's buffer allocation throws std::bad_alloc on the worker. +// The stand-in is a DLL with its own C++ runtime, so replacing operator new here would not reach it; +// the commit limit is the one seam that works the same on the real worker. +// +// Checks, on one queue: a normal request succeeds; the oversized request completes with a failure +// status (within a timeout, destination unchanged); a normal request submitted afterwards succeeds +// with correct data. Returns 77 where the system does not enforce the job limit. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include + +#include +#include +#include + +namespace { + +using u64 = std::uint64_t; +constexpr int skipped = 77; +constexpr SIZE_T commit_headroom = SIZE_T{256} << 20; // job limit above the current commit +constexpr unsigned oversized_inflated = 1536u << 20; // declared inflated size, above the limit +constexpr DWORD completion_timeout_ms = 15000; + +struct Object { void** vtable; }; +using GetFactoryFn = long(__stdcall*)(const void*, void**); +using CreateStatusArrayFn = long(__stdcall*)(void*, unsigned, const char*, const void*, void**); +using CreateQueueFn = long(__stdcall*)(void*, const void*, const void*, void**); +using EnqueueRequestFn = void(__stdcall*)(void*, const void*); +using EnqueueStatusFn = void(__stdcall*)(void*, void*, unsigned); +using SubmitFn = void(__stdcall*)(void*); +using IsCompleteFn = bool(__stdcall*)(void*, unsigned); +using GetHResultFn = long(__stdcall*)(void*, unsigned); + +std::uint32_t adler32(const unsigned char* data, std::size_t size) +{ + std::uint32_t a = 1, b = 0; + for (std::size_t i = 0; i < size; ++i) { + a = (a + data[i]) % 65521; + b = (b + a) % 65521; + } + return (b << 16) | a; +} + +// A zlib stream of one stored block (size at most 65535). +std::vector stored_zlib(const std::vector& plain) +{ + const auto size = static_cast(plain.size()); + std::vector out{0x78, 0x01, 0x01, static_cast(size), static_cast(size >> 8), + static_cast(~size), static_cast((~size) >> 8)}; + out.insert(out.end(), plain.begin(), plain.end()); + const std::uint32_t sum = adler32(plain.data(), plain.size()); + for (int shift = 24; shift >= 0; shift -= 8) out.push_back(static_cast(sum >> shift)); + return out; +} + +struct Queue { + Object* queue = nullptr; + Object* status = nullptr; + + // Enqueues a memory-source zlib request into a linear destination and a status entry, submits, + // and waits for the status. Returns false on a timeout; hr receives the status. + bool run(std::vector& destination, const std::vector& stream, unsigned inflated, + unsigned index, long& hr) const + { + unsigned char request[0x48] = {}; + *reinterpret_cast(request + 0x00) = 1 | 0x400000; + *reinterpret_cast(request + 0x08) = destination.data(); + *reinterpret_cast(request + 0x18) = static_cast(destination.size()); + *reinterpret_cast(request + 0x20) = stream.data(); + *reinterpret_cast(request + 0x30) = static_cast(stream.size()); + *reinterpret_cast(request + 0x38) = inflated; + reinterpret_cast(queue->vtable[3])(queue, request); + reinterpret_cast(queue->vtable[4])(queue, status, index); + reinterpret_cast(queue->vtable[6])(queue); + const DWORD start = GetTickCount(); + while (!reinterpret_cast(status->vtable[3])(status, index)) { + if (GetTickCount() - start > completion_timeout_ms) return false; + Sleep(5); + } + hr = reinterpret_cast(status->vtable[4])(status, index); + return true; + } +}; + +// Limits this process's commit to a little above what it holds now. False where that cannot be done. +bool cap_commit() +{ + PROCESS_MEMORY_COUNTERS counters{}; + if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof counters)) return false; + HANDLE job = CreateJobObjectW(nullptr, nullptr); + if (!job) return false; + JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{}; + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY; + limits.ProcessMemoryLimit = counters.PeakPagefileUsage + commit_headroom; + return SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits, sizeof limits) && + AssignProcessToJobObject(job, GetCurrentProcess()); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) { + std::fprintf(stderr, "usage: startup_storage_alloc_failure XCRDAPI.dll\n"); + return 2; + } + HMODULE library = LoadLibraryA(argv[1]); + auto* get_factory = library ? reinterpret_cast(GetProcAddress(library, "DStorageGetFactory")) : nullptr; + void* factory_ptr = nullptr; + if (!get_factory || get_factory(nullptr, &factory_ptr) != 0 || !factory_ptr) { + std::fprintf(stderr, "cannot load the DirectStorage stand-in\n"); + return 1; + } + auto* factory = static_cast(factory_ptr); + Queue queue; + void* status_ptr = nullptr; + void* queue_ptr = nullptr; + unsigned char description[0x20] = {}; + *reinterpret_cast(description + 8) = 16; + if (reinterpret_cast(factory->vtable[5])(factory, 3, "Status", nullptr, &status_ptr) != 0 || + reinterpret_cast(factory->vtable[10])(factory, description, nullptr, &queue_ptr) != 0) { + std::fprintf(stderr, "cannot create the queue\n"); + return 1; + } + queue.status = static_cast(status_ptr); + queue.queue = static_cast(queue_ptr); + + std::vector plain(60000); + for (std::size_t i = 0; i < plain.size(); ++i) plain[i] = static_cast((i % 251) ^ 0x5a); + const auto stream = stored_zlib(plain); + const unsigned plain_size = static_cast(plain.size()); + + long hr = -1; + std::vector first(plain.size(), 0xAA); + if (!queue.run(first, stream, plain_size, 0, hr) || hr != 0 || first != plain) { + std::fprintf(stderr, "the baseline request did not succeed (hr 0x%08lx)\n", static_cast(hr)); + return 1; + } + + if (!cap_commit()) { + std::puts("cannot place the process under a commit limit"); + return skipped; + } + void* probe = VirtualAlloc(nullptr, oversized_inflated, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (probe) { + VirtualFree(probe, 0, MEM_RELEASE); + std::puts("the commit limit is not enforced on this system"); + return skipped; + } + + std::vector failing(plain.size(), 0xAA); + if (!queue.run(failing, stream, oversized_inflated, 1, hr)) { + std::fprintf(stderr, "the request that hit an allocation failure never completed\n"); + return 1; + } + if (hr >= 0) { + std::fprintf(stderr, "the request that hit an allocation failure reported success (hr 0x%08lx)\n", + static_cast(hr)); + return 1; + } + for (unsigned char byte : failing) + if (byte != 0xAA) { + std::fprintf(stderr, "the failed request changed its destination\n"); + return 1; + } + + std::vector after(plain.size(), 0xAA); + if (!queue.run(after, stream, plain_size, 2, hr) || hr != 0 || after != plain) { + std::fprintf(stderr, "the worker did not serve a request after the failure (hr 0x%08lx)\n", static_cast(hr)); + return 1; + } + std::puts("allocation failure failed the request; the worker served the next one"); + return 0; +} From 79270eb02c536f4e9c75405a78e95fbee649ec95 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:06:45 +0100 Subject: [PATCH 087/775] runtime: roll back queue work if worker startup fails --- src/startup_stubs/xcrdapi.cpp | 70 ++++++++++++++------ tests/startup_storage_alloc_failure.cpp | 88 +++++++++++++++++++++++++ 2 files changed, 138 insertions(+), 20 deletions(-) diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index f4e8e5f21..4b9b5ab01 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -666,44 +666,74 @@ DWORD WINAPI queue_worker(void* parameter) } } -QueueWork& work_of(Object* self) +QueueWork* ensure_work(Object* self) { static std::mutex create; const std::lock_guard guard(create); - if (!self->work) { - self->work = new QueueWork; - HANDLE worker = CreateThread(nullptr, worker_stack_commit, queue_worker, self, 0, nullptr); - if (!worker) worker = CreateThread(nullptr, 0, queue_worker, self, 0, nullptr); - if (worker) CloseHandle(worker); - else log("x2w-dstorage queue worker not started: error %lu", GetLastError()); + if (self->work) return self->work; + auto* work = new (std::nothrow) QueueWork; + if (!work) { + log("x2w-dstorage queue work allocation failed"); + return nullptr; + } + HANDLE worker = CreateThread(nullptr, worker_stack_commit, queue_worker, self, CREATE_SUSPENDED, nullptr); + if (!worker) worker = CreateThread(nullptr, 0, queue_worker, self, CREATE_SUSPENDED, nullptr); + if (!worker) { + log("x2w-dstorage queue worker not started: error %lu", GetLastError()); + delete work; + return nullptr; + } + self->work = work; + ResumeThread(worker); + CloseHandle(worker); + return work; +} + +void fail_unstarted_entry(Object* self, const Entry& entry) +{ + if (entry.type == Entry::request) { + InterlockedIncrement(&requests_failed); + InterlockedCompareExchange(&self->pending, static_cast(E_OUTOFMEMORY), S_OK); + } else if (entry.type == Entry::status_entry) { + const LONG pending = InterlockedExchange(&self->pending, S_OK); + if (entry.array && entry.array->results && entry.index < entry.array->capacity) { + InterlockedExchange(&entry.array->results[entry.index], + pending < 0 ? pending : static_cast(E_OUTOFMEMORY)); + } + } else { + signal_fence(entry.fence, entry.value); } - return *self->work; } void submit(Object* self) { - QueueWork& work = work_of(self); + QueueWork* work = ensure_work(self); + if (!work) return; { - const std::lock_guard guard(work.mutex); - const u64 submission_id = ++work.next_submission_id; - for (auto& entry : work.waiting) { + const std::lock_guard guard(work->mutex); + const u64 submission_id = ++work->next_submission_id; + for (auto& entry : work->waiting) { entry.submission_id = submission_id; - work.submitted.push_back(std::move(entry)); + work->submitted.push_back(std::move(entry)); } - work.waiting.clear(); + work->waiting.clear(); } - work.wake.notify_one(); + work->wake.notify_one(); } void push(Object* self, Entry&& entry) { - QueueWork& work = work_of(self); + QueueWork* work = ensure_work(self); + if (!work) { + fail_unstarted_entry(self, entry); + return; + } bool full; { - const std::lock_guard guard(work.mutex); - entry.id = ++work.next_entry_id; - work.waiting.push_back(std::move(entry)); - full = self->capacity && work.waiting.size() >= self->capacity; + const std::lock_guard guard(work->mutex); + entry.id = ++work->next_entry_id; + work->waiting.push_back(std::move(entry)); + full = self->capacity && work->waiting.size() >= self->capacity; } if (full) submit(self); // a full queue submits itself, as on PC } diff --git a/tests/startup_storage_alloc_failure.cpp b/tests/startup_storage_alloc_failure.cpp index b60119873..639c0f323 100644 --- a/tests/startup_storage_alloc_failure.cpp +++ b/tests/startup_storage_alloc_failure.cpp @@ -38,10 +38,24 @@ using CreateStatusArrayFn = long(__stdcall*)(void*, unsigned, const char*, const using CreateQueueFn = long(__stdcall*)(void*, const void*, const void*, void**); using EnqueueRequestFn = void(__stdcall*)(void*, const void*); using EnqueueStatusFn = void(__stdcall*)(void*, void*, unsigned); +using EnqueueSignalFn = void(__stdcall*)(void*, void*, u64); using SubmitFn = void(__stdcall*)(void*); using IsCompleteFn = bool(__stdcall*)(void*, unsigned); using GetHResultFn = long(__stdcall*)(void*, unsigned); +struct MockFence { + void** vtable; + bool signaled = false; + u64 value = 0; + static long __stdcall signal(void* self, u64 val) + { + auto* f = static_cast(self); + f->signaled = true; + f->value = val; + return 0; + } +}; + std::uint32_t adler32(const unsigned char* data, std::size_t size) { std::uint32_t a = 1, b = 0; @@ -180,6 +194,80 @@ int main(int argc, char** argv) std::fprintf(stderr, "the worker did not serve a request after the failure (hr 0x%08lx)\n", static_cast(hr)); return 1; } + + // Also verify that if worker thread creation fails on a fresh queue under commit exhaustion, + // enqueued status/signal entries complete with failure instead of hanging at E_PENDING, and + // the queue recovers once commit is freed. + Queue recovery_queue; + void* status2_ptr = nullptr; + void* queue2_ptr = nullptr; + if (reinterpret_cast(factory->vtable[5])(factory, 2, "Status2", nullptr, &status2_ptr) != 0 || + reinterpret_cast(factory->vtable[10])(factory, description, nullptr, &queue2_ptr) != 0) { + std::fprintf(stderr, "cannot create the recovery queue\n"); + return 1; + } + recovery_queue.status = static_cast(status2_ptr); + recovery_queue.queue = static_cast(queue2_ptr); + + std::vector during_exhaustion(plain.size(), 0xAA); + std::vector after_recovery(plain.size(), 0xAA); + std::vector held; + held.reserve(4096); + for (SIZE_T chunk : {SIZE_T{1} << 20, SIZE_T{64} << 10}) { + while (held.size() < held.capacity()) { + void* p = VirtualAlloc(nullptr, chunk, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!p) break; + held.push_back(p); + } + } + if (held.size() < held.capacity()) { + if (void* region = VirtualAlloc(nullptr, SIZE_T{64} << 10, MEM_RESERVE, PAGE_READWRITE)) { + held.push_back(region); + for (SIZE_T off = 0; off < (SIZE_T{64} << 10); off += 4096) { + if (!VirtualAlloc(static_cast(region) + off, 4096, MEM_COMMIT, PAGE_READWRITE)) break; + } + } + } + + void* fence_vtable[11] = {}; + fence_vtable[10] = reinterpret_cast(&MockFence::signal); + MockFence fence{fence_vtable}; + + unsigned char req[0x48] = {}; + *reinterpret_cast(req + 0x00) = 1 | 0x400000; + *reinterpret_cast(req + 0x08) = during_exhaustion.data(); + *reinterpret_cast(req + 0x18) = static_cast(during_exhaustion.size()); + *reinterpret_cast(req + 0x20) = stream.data(); + *reinterpret_cast(req + 0x30) = static_cast(stream.size()); + *reinterpret_cast(req + 0x38) = plain_size; + + reinterpret_cast(recovery_queue.queue->vtable[3])(recovery_queue.queue, req); + reinterpret_cast(recovery_queue.queue->vtable[4])(recovery_queue.queue, recovery_queue.status, 0); + reinterpret_cast(recovery_queue.queue->vtable[5])(recovery_queue.queue, &fence, 0x1234ull); + reinterpret_cast(recovery_queue.queue->vtable[6])(recovery_queue.queue); + + const bool completed_immediately = + reinterpret_cast(recovery_queue.status->vtable[3])(recovery_queue.status, 0); + const long exhausted_hr = + reinterpret_cast(recovery_queue.status->vtable[4])(recovery_queue.status, 0); + + for (void* p : held) VirtualFree(p, 0, MEM_RELEASE); + held.clear(); + + if (!completed_immediately || exhausted_hr >= 0 || !fence.signaled || fence.value != 0x1234ull) { + std::fprintf(stderr, + "worker-startup failure did not fail cleanly (complete=%d hr=0x%08lx signaled=%d val=0x%llx)\n", + completed_immediately ? 1 : 0, static_cast(exhausted_hr), fence.signaled ? 1 : 0, + static_cast(fence.value)); + return 1; + } + + if (!recovery_queue.run(after_recovery, stream, plain_size, 1, hr) || hr != 0 || after_recovery != plain) { + std::fprintf(stderr, "the queue did not recover after worker startup failure (hr 0x%08lx)\n", + static_cast(hr)); + return 1; + } + std::puts("allocation failure failed the request; the worker served the next one"); return 0; } From fa7735b2cede0b2c05d52e45b30ef2b9613eebaf Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:22:57 +0100 Subject: [PATCH 088/775] runtime: defer queue failure effects to Submit and survive a throwing queue construction The queue's work holds three std::deque members whose constructors allocate, so new (std::nothrow) can still throw std::bad_alloc; construction now catches it and treats it like a null result. Building the work and starting the worker are separate steps: Enqueue only records an entry (in the work, or in a small record that needs no queue storage) and never completes a status entry or signals a fence. Submit retries both steps; if the worker still cannot start, the recorded entries fail there with the pending failure and their fences are signaled. startup_storage_worker_start compiles the stand-in into the test, redirects CreateThread and replaces operator new to fail on demand, and checks pending status and an unsignaled fence before Submit, failure status and a signaled fence after it, a retry that starts the worker, and a correct request afterwards. --- CMakeLists.txt | 9 + docs/startup-runtime.md | 14 ++ src/startup_stubs/xcrdapi.cpp | 131 ++++++++-- tests/startup_storage_worker_start.cpp | 319 +++++++++++++++++++++++++ 4 files changed, 457 insertions(+), 16 deletions(-) create mode 100644 tests/startup_storage_worker_start.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6828be35d..8f8f5c04a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -346,6 +346,15 @@ target_link_libraries(startup_storage_alloc_failure PRIVATE psapi) add_dependencies(startup_storage_alloc_failure startup_stub_xcrdapi) add_test(NAME startup_storage_alloc_failure COMMAND startup_storage_alloc_failure "$") set_tests_properties(startup_storage_alloc_failure PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) +# A queue whose worker cannot start (both CreateThread attempts fail, or the construction of its work +# throws std::bad_alloc) completes status entries and fences at Submit, never inside Enqueue (#1199). +# The test compiles the stand-in's source into itself so it can redirect CreateThread and operator new. +add_executable(startup_storage_worker_start tests/startup_storage_worker_start.cpp) +target_compile_features(startup_storage_worker_start PRIVATE cxx_std_17) +target_include_directories(startup_storage_worker_start PRIVATE src) +target_link_libraries(startup_storage_worker_start PRIVATE psapi) +add_test(NAME startup_storage_worker_start COMMAND startup_storage_worker_start) +set_tests_properties(startup_storage_worker_start PROPERTIES TIMEOUT 60) target_compile_features(startup_stub_consumer PRIVATE cxx_std_17) target_link_libraries(startup_stub_consumer PRIVATE startup_stub_chad startup_stub_xg_xs xmem_shim d3d12_xs_shim) # APU heap stand-in: ApuFree reuse, coalescing, refused requests and concurrent callers (docs/startup-runtime.md). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 43519bf3b..9ccb93cee 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -412,6 +412,20 @@ These are measured on one executable; treat them as hypotheses for others. then a correct result for a normal request on the same queue. It returns 77 where the limit is not enforced. Reproduce with `ctest --preset release --no-tests=error -R '^startup_storage_alloc_failure$' -V`. + A queue builds its work (three `std::deque`s, whose constructors allocate and can throw + `std::bad_alloc` even under `new (std::nothrow)`) and starts its worker separately. Enqueue + only records an entry, in the work when it exists, otherwise in a small record that needs no + queue storage; it never completes a status entry or signals a fence. Submit retries the + construction and the worker start (a committed-stack attempt, then a default-stack one). If the + worker runs, the entries proceed as usual. If it cannot start, every recorded entry fails there: + its status entry takes the pending failure (`E_OUTOFMEMORY` when nothing worse is pending) and + its fence is signaled, so nothing is left at `E_PENDING`. An entry that could not even be + recorded loses its request bytes, so it fails at Submit even if the worker starts then; only when + the small record itself cannot be allocated is the entry failed inside Enqueue. + `startup_storage_worker_start` compiles the stand-in into the test, redirects `CreateThread` + and replaces `operator new` to make both failures on demand, and checks pending status and an + unsignaled fence before Submit, failure status and a signaled fence after it, and a correct + request on the same queue afterwards. ## Shortcuts that are known to be wrong diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 4b9b5ab01..6500cfbe1 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -52,6 +52,8 @@ struct Object { LONG* results; // StatusArray: one HRESULT per index, E_PENDING until a status is enqueued LONG pending; // Queue: worst HRESULT of the requests since the last status struct QueueWork* work = nullptr; // Queue: entries waiting for Submit and the worker running them + struct Unrecorded* unrecorded_head = nullptr; // Queue: entries no queue storage could hold, see push() + struct Unrecorded* unrecorded_tail = nullptr; }; // A queue entry as enqueued: a request (its 0x48 bytes copied, and a snapshot of its destination page @@ -82,6 +84,7 @@ struct QueueWork { std::mutex mutex; std::condition_variable wake; std::deque waiting, submitted; + bool worker_started = false; // guarded by the setup mutex u64 next_entry_id = 0; u64 next_submission_id = 0; static constexpr std::size_t max_cached_streams = 16; @@ -666,49 +669,136 @@ DWORD WINAPI queue_worker(void* parameter) } } +// Guards queue setup: building a queue's work, starting its worker and the unrecorded list. +std::mutex& setup_mutex() +{ + static std::mutex setup; + return setup; +} + +// Builds the queue's work once. The three deques allocate in their constructors, so even +// new (std::nothrow) can throw std::bad_alloc from here: that is treated like a null result, and +// nothing escapes to the title. The failure is logged after the handler has left. QueueWork* ensure_work(Object* self) { - static std::mutex create; - const std::lock_guard guard(create); + const std::lock_guard guard(setup_mutex()); if (self->work) return self->work; - auto* work = new (std::nothrow) QueueWork; + QueueWork* work = nullptr; + try { + work = new (std::nothrow) QueueWork; + } catch (const std::bad_alloc&) { + work = nullptr; + } if (!work) { log("x2w-dstorage queue work allocation failed"); return nullptr; } + self->work = work; + return work; +} + +// Starts the queue's worker unless it runs. The worker is created suspended with a committed stack, +// then once more with the default stack; false when neither thread could be created, which leaves +// the queue as it was so a later call tries again. +bool start_worker(Object* self, QueueWork* work) +{ + const std::lock_guard guard(setup_mutex()); + if (work->worker_started) return true; HANDLE worker = CreateThread(nullptr, worker_stack_commit, queue_worker, self, CREATE_SUSPENDED, nullptr); if (!worker) worker = CreateThread(nullptr, 0, queue_worker, self, CREATE_SUSPENDED, nullptr); if (!worker) { log("x2w-dstorage queue worker not started: error %lu", GetLastError()); - delete work; - return nullptr; + return false; } - self->work = work; + work->worker_started = true; ResumeThread(worker); CloseHandle(worker); - return work; + return true; } -void fail_unstarted_entry(Object* self, const Entry& entry) +// What an entry that could not be stored needs in order to fail at Submit: no request bytes, since a +// request only counts as failed. +struct Unrecorded { + Unrecorded* next; + Entry::Type type; + Object* array; + unsigned index; + void* fence; + u64 value; +}; + +// Fails an entry that will not run: a request counts as failed, a status entry completes with the +// pending failure (E_OUTOFMEMORY when nothing worse is pending), a fence is signaled. +void fail_unstarted(Object* self, Entry::Type type, Object* array, unsigned index, void* fence, u64 value) { - if (entry.type == Entry::request) { + if (type == Entry::request) { InterlockedIncrement(&requests_failed); InterlockedCompareExchange(&self->pending, static_cast(E_OUTOFMEMORY), S_OK); - } else if (entry.type == Entry::status_entry) { + } else if (type == Entry::status_entry) { const LONG pending = InterlockedExchange(&self->pending, S_OK); - if (entry.array && entry.array->results && entry.index < entry.array->capacity) { - InterlockedExchange(&entry.array->results[entry.index], + if (array && array->results && index < array->capacity) { + InterlockedExchange(&array->results[index], pending < 0 ? pending : static_cast(E_OUTOFMEMORY)); } } else { - signal_fence(entry.fence, entry.value); + signal_fence(fence, value); + } +} + +// An entry the queue has no room for (its work could not be built or grown): remembered in a small +// record that needs no queue storage, failed by the next Submit. Only when even that record cannot be +// allocated is the entry failed here, because nothing is left to remember it with. +void defer_unrecorded(Object* self, const Entry& entry) +{ + auto* node = new (std::nothrow) Unrecorded{nullptr, entry.type, entry.array, entry.index, entry.fence, entry.value}; + if (!node) { + fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value); + return; + } + const std::lock_guard guard(setup_mutex()); + (self->unrecorded_tail ? self->unrecorded_tail->next : self->unrecorded_head) = node; + self->unrecorded_tail = node; +} + +void fail_unrecorded(Object* self) +{ + Unrecorded* node; + { + const std::lock_guard guard(setup_mutex()); + node = self->unrecorded_head; + self->unrecorded_head = self->unrecorded_tail = nullptr; + } + while (node) { + Unrecorded* const next = node->next; + fail_unstarted(self, node->type, node->array, node->index, node->fence, node->value); + delete node; + node = next; } } +// Submit: entries that could not be stored fail now; waiting entries go to the worker, which is +// started if it is not running yet (resources may have recovered since Enqueue). If it still cannot +// be started, the waiting entries fail too: their status entries and fences complete here, not +// earlier in Enqueue. void submit(Object* self) { QueueWork* work = ensure_work(self); + const bool started = work && start_worker(self, work); + fail_unrecorded(self); if (!work) return; + if (!started) { + for (;;) { + Entry entry{}; + { + const std::lock_guard guard(work->mutex); + if (work->waiting.empty()) break; + entry = std::move(work->waiting.front()); + work->waiting.pop_front(); + } + fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value); + } + return; + } { const std::lock_guard guard(work->mutex); const u64 submission_id = ++work->next_submission_id; @@ -721,19 +811,28 @@ void submit(Object* self) work->wake.notify_one(); } +// Enqueue only records the entry, whether or not a worker runs; nothing completes before Submit. void push(Object* self, Entry&& entry) { QueueWork* work = ensure_work(self); if (!work) { - fail_unstarted_entry(self, entry); + defer_unrecorded(self, entry); return; } - bool full; - { + start_worker(self, work); // a failure shows at Submit + bool recorded = false; + bool full = false; + try { const std::lock_guard guard(work->mutex); entry.id = ++work->next_entry_id; work->waiting.push_back(std::move(entry)); + recorded = true; full = self->capacity && work->waiting.size() >= self->capacity; + } catch (const std::bad_alloc&) { + } + if (!recorded) { + defer_unrecorded(self, entry); + return; } if (full) submit(self); // a full queue submits itself, as on PC } diff --git a/tests/startup_storage_worker_start.cpp b/tests/startup_storage_worker_start.cpp new file mode 100644 index 000000000..4ceccab17 --- /dev/null +++ b/tests/startup_storage_worker_start.cpp @@ -0,0 +1,319 @@ +// A DirectStorage queue whose worker cannot be started keeps the deferred-completion contract +// (#1199, item 3): Enqueue never completes a status entry or signals a fence, and Submit does. +// +// Two failures are made on demand inside the stand-in, which this test compiles into itself instead +// of loading as a DLL, so it shares the test's allocator and CreateThread: +// - CreateThread is redirected, for the stand-in's translation unit only, to a function that can +// fail every thread creation (both the committed-stack attempt and the default-stack attempt); +// - operator new is replaced with one that throws std::bad_alloc on the calling thread when armed. +// The queue's three std::deque members allocate in their constructors, so the construction of +// the queue's work throws although the work itself is allocated with new (std::nothrow). +// +// Checks, each on a fresh queue: with no worker, before Submit the status entry is still pending, the +// fence is not signaled and the destination is untouched; after Submit the status entry holds a +// failure and the fence is signaled; with a throwing queue construction no exception reaches the caller +// and the same holds; and once the failure is gone a request on the same queue returns correct data. +// A worker that cannot start at Enqueue but can at Submit runs the entries normally. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include +#include +#include +#include + +namespace { +std::atomic fail_thread_creation{false}; +std::atomic thread_attempts{0}; +thread_local bool throw_on_new = false; +std::atomic thrown{0}; + +HANDLE WINAPI creator_under_test(LPSECURITY_ATTRIBUTES attributes, SIZE_T stack, LPTHREAD_START_ROUTINE start, + LPVOID parameter, DWORD flags, LPDWORD id) +{ + ++thread_attempts; + if (fail_thread_creation) { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return nullptr; + } + return CreateThread(attributes, stack, start, parameter, flags, id); +} +} // namespace + +void* operator new(std::size_t size) +{ + if (throw_on_new) { + ++thrown; + throw std::bad_alloc(); + } + if (void* memory = std::malloc(size ? size : 1)) return memory; + throw std::bad_alloc(); +} +void* operator new(std::size_t size, const std::nothrow_t&) noexcept { return std::malloc(size ? size : 1); } +void operator delete(void* memory) noexcept { std::free(memory); } +void operator delete(void* memory, std::size_t) noexcept { std::free(memory); } +void operator delete(void* memory, const std::nothrow_t&) noexcept { std::free(memory); } + +#define CreateThread creator_under_test +#include "startup_stubs/xcrdapi.cpp" +#undef CreateThread + +namespace { + +constexpr LONG pending_status = static_cast(0x8000000A); +constexpr DWORD completion_timeout_ms = 15000; +constexpr unsigned char untouched = 0xAA; + +using CreateStatusArrayFn = long(__stdcall*)(void*, unsigned, const char*, const void*, void**); +using CreateQueueFn = long(__stdcall*)(void*, const void*, const void*, void**); +using EnqueueRequestFn = void(__stdcall*)(void*, const void*); +using EnqueueStatusFn = void(__stdcall*)(void*, void*, unsigned); +using EnqueueSignalFn = void(__stdcall*)(void*, void*, std::uint64_t); +using SubmitFn = void(__stdcall*)(void*); +using IsCompleteFn = bool(__stdcall*)(void*, unsigned); +using GetHResultFn = long(__stdcall*)(void*, unsigned); + +struct MockFence { + void** vtable; + int signals = 0; + std::uint64_t value = 0; + static long __stdcall signal(void* self, std::uint64_t value) + { + auto* fence = static_cast(self); + ++fence->signals; + fence->value = value; + return 0; + } +}; + +struct Vtables { + void* fence[11] = {}; + Vtables() { fence[10] = reinterpret_cast(&MockFence::signal); } +}; + +std::uint32_t adler32(const unsigned char* data, std::size_t size) +{ + std::uint32_t a = 1, b = 0; + for (std::size_t i = 0; i < size; ++i) { + a = (a + data[i]) % 65521; + b = (b + a) % 65521; + } + return (b << 16) | a; +} + +// A zlib stream of one stored block (size at most 65535). +std::vector stored_zlib(const std::vector& plain) +{ + const auto size = static_cast(plain.size()); + std::vector out{0x78, 0x01, 0x01, static_cast(size), static_cast(size >> 8), + static_cast(~size), static_cast((~size) >> 8)}; + out.insert(out.end(), plain.begin(), plain.end()); + const std::uint32_t sum = adler32(plain.data(), plain.size()); + for (int shift = 24; shift >= 0; shift -= 8) out.push_back(static_cast(sum >> shift)); + return out; +} + +struct Fixture { + Object* factory = nullptr; + std::vector plain, stream; + Vtables vtables; + const char* error = nullptr; + + struct Queue { + Object* queue = nullptr; + Object* status = nullptr; + MockFence fence; + }; + + bool create(Queue& q, Vtables& v) const + { + void* status = nullptr; + void* queue = nullptr; + unsigned char description[0x20] = {}; + *reinterpret_cast(description + 8) = 16; + if (reinterpret_cast(factory->vtable[5])(factory, 4, "Status", nullptr, &status) != 0 || + reinterpret_cast(factory->vtable[10])(factory, description, nullptr, &queue) != 0) + return false; + q.status = static_cast(status); + q.queue = static_cast(queue); + q.fence.vtable = v.fence; + return true; + } + + void request(const Queue& q, std::vector& destination) const + { + unsigned char bytes[0x48] = {}; + *reinterpret_cast(bytes + 0x00) = 1 | 0x400000; + *reinterpret_cast(bytes + 0x08) = destination.data(); + *reinterpret_cast(bytes + 0x18) = static_cast(destination.size()); + *reinterpret_cast(bytes + 0x20) = stream.data(); + *reinterpret_cast(bytes + 0x30) = static_cast(stream.size()); + *reinterpret_cast(bytes + 0x38) = static_cast(plain.size()); + reinterpret_cast(q.queue->vtable[3])(q.queue, bytes); + } + void status_entry(const Queue& q, unsigned index) const + { + reinterpret_cast(q.queue->vtable[4])(q.queue, q.status, index); + } + void signal(Queue& q, std::uint64_t value) const + { + reinterpret_cast(q.queue->vtable[5])(q.queue, &q.fence, value); + } + void submit(const Queue& q) const { reinterpret_cast(q.queue->vtable[6])(q.queue); } + bool complete(const Queue& q, unsigned index) const + { + return reinterpret_cast(q.status->vtable[3])(q.status, index); + } + long hresult(const Queue& q, unsigned index) const + { + return reinterpret_cast(q.status->vtable[4])(q.status, index); + } + bool wait(const Queue& q, unsigned index) const + { + const DWORD start = GetTickCount(); + while (!complete(q, index)) { + if (GetTickCount() - start > completion_timeout_ms) return false; + Sleep(5); + } + return true; + } +}; + +bool fail(const char* what) +{ + std::fprintf(stderr, "FAIL: %s\n", what); + return false; +} + +bool untouched_bytes(const std::vector& bytes) +{ + for (unsigned char byte : bytes) + if (byte != untouched) return false; + return true; +} + +// A request, a status entry and a fence signal are enqueued; nothing may complete until Submit. +// before_enqueue / before_submit let the caller arm a failure around each step. +template +bool enqueue_without_effects(Fixture& f, Fixture::Queue& q, std::vector& destination, Arm arm) +{ + try { + arm(true); + f.request(q, destination); + f.status_entry(q, 0); + f.signal(q, 7); + arm(false); + } catch (...) { + arm(false); + return fail("an exception left an Enqueue call"); + } + if (f.complete(q, 0) || f.hresult(q, 0) != pending_status) return fail("the status entry completed inside Enqueue"); + if (q.fence.signals != 0 || q.fence.value != 0) return fail("the fence was signaled inside Enqueue"); + if (!untouched_bytes(destination)) return fail("the destination changed inside Enqueue"); + return true; +} + +bool failed_at_submit(Fixture& f, Fixture::Queue& q) +{ + if (!f.complete(q, 0) || f.hresult(q, 0) >= 0) return fail("Submit did not complete the status entry with a failure"); + if (q.fence.signals != 1 || q.fence.value != 7) return fail("Submit did not signal the fence once with its value"); + return true; +} + +bool serves_next_request(Fixture& f, Fixture::Queue& q) +{ + std::vector destination(f.plain.size(), untouched); + f.request(q, destination); + f.status_entry(q, 1); + f.submit(q); + if (!f.wait(q, 1)) return fail("a request after the failure never completed"); + if (f.hresult(q, 1) != 0 || destination != f.plain) return fail("a request after the failure returned wrong data"); + return true; +} + +// Both CreateThread attempts fail at Enqueue and at Submit. +bool worker_cannot_start(Fixture& f) +{ + Fixture::Queue q; + if (!f.create(q, f.vtables)) return fail("cannot create the queue"); + std::vector destination(f.plain.size(), untouched); + fail_thread_creation = true; + thread_attempts = 0; + const bool effects_deferred = enqueue_without_effects(f, q, destination, [](bool) {}); + const int attempts = thread_attempts; + f.submit(q); + fail_thread_creation = false; + if (!effects_deferred) return false; + if (attempts < 2) return fail("the worker start did not try both stack sizes"); + if (!failed_at_submit(f, q)) return false; + if (!untouched_bytes(destination)) return fail("the failed request changed its destination"); + return serves_next_request(f, q); +} + +// The worker cannot start at Enqueue but can by Submit: the entries run normally. +bool worker_starts_at_submit(Fixture& f) +{ + Fixture::Queue q; + if (!f.create(q, f.vtables)) return fail("cannot create the queue"); + std::vector destination(f.plain.size(), untouched); + fail_thread_creation = true; + const bool effects_deferred = enqueue_without_effects(f, q, destination, [](bool) {}); + fail_thread_creation = false; + if (!effects_deferred) return false; + f.submit(q); + if (!f.wait(q, 0) || f.hresult(q, 0) != 0 || destination != f.plain) return fail("the retried worker did not run the request"); + const DWORD start = GetTickCount(); + while (q.fence.signals == 0 && GetTickCount() - start < completion_timeout_ms) Sleep(5); + if (q.fence.signals != 1 || q.fence.value != 7) return fail("the retried worker did not signal the fence"); + return true; +} + +// Constructing the queue's work throws std::bad_alloc, at Enqueue and also at Submit. +bool construction_throws(Fixture& f, bool throw_at_submit) +{ + Fixture::Queue q; + if (!f.create(q, f.vtables)) return fail("cannot create the queue"); + std::vector destination(f.plain.size(), untouched); + thrown = 0; + const bool effects_deferred = enqueue_without_effects(f, q, destination, [](bool on) { throw_on_new = on; }); + if (!effects_deferred) return false; + if (thrown == 0) return fail("the queue construction never threw: the control did not reach the deques"); + try { + throw_on_new = throw_at_submit; + f.submit(q); + throw_on_new = false; + } catch (...) { + throw_on_new = false; + return fail("an exception left Submit"); + } + if (!failed_at_submit(f, q)) return false; + if (!untouched_bytes(destination)) return fail("the failed request changed its destination"); + return serves_next_request(f, q); +} + +} // namespace + +int main() +{ + void* factory = nullptr; + if (DStorageGetFactory(nullptr, &factory) != 0 || !factory) return fail("cannot get the factory"), 1; + Fixture f; + f.factory = static_cast(factory); + f.plain.resize(60000); + for (std::size_t i = 0; i < f.plain.size(); ++i) f.plain[i] = static_cast((i % 251) ^ 0x5a); + f.stream = stored_zlib(f.plain); + + if (!worker_cannot_start(f)) return 1; + if (!worker_starts_at_submit(f)) return 1; + if (!construction_throws(f, false)) return 1; + if (!construction_throws(f, true)) return 1; + std::puts("a queue that cannot start its worker completes status and fences at Submit, and recovers"); + return 0; +} From 3c15831363325b3eaa34abb4d9c8864feceb51f7 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:32:50 +0100 Subject: [PATCH 089/775] runtime: fail every single allocation point of DirectStorage Enqueue and Submit without an exception --- docs/startup-runtime.md | 11 +- src/startup_stubs/xcrdapi.cpp | 53 ++++--- tests/startup_storage_worker_start.cpp | 184 ++++++++++++++++++++----- 3 files changed, 193 insertions(+), 55 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9ccb93cee..b0bbaba94 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -421,11 +421,14 @@ These are measured on one executable; treat them as hypotheses for others. its status entry takes the pending failure (`E_OUTOFMEMORY` when nothing worse is pending) and its fence is signaled, so nothing is left at `E_PENDING`. An entry that could not even be recorded loses its request bytes, so it fails at Submit even if the worker starts then; only when - the small record itself cannot be allocated is the entry failed inside Enqueue. + the small record itself cannot be allocated is the entry failed inside Enqueue. No exception + leaves Enqueue or Submit: a request whose page tokens cannot be copied is recorded the same way, + and if Submit cannot grow the worker's list the entries still waiting fail there. `startup_storage_worker_start` compiles the stand-in into the test, redirects `CreateThread` - and replaces `operator new` to make both failures on demand, and checks pending status and an - unsignaled fence before Submit, failure status and a signaled fence after it, and a correct - request on the same queue afterwards. + and replaces `operator new` with one that fails the N-th allocation once and then behaves + normally. It sweeps N over Enqueue and Submit, and checks pending status and an unsignaled fence + before Submit, then a request that completed with correct data or a failure, a fence signaled + once, and a correct request on the same queue afterwards. A crash names the stage it was in. ## Shortcuts that are known to be wrong diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 6500cfbe1..1f163ed93 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -776,10 +776,25 @@ void fail_unrecorded(Object* self) } } +// Fails every entry still waiting, in order; none of them will run. +void fail_waiting(Object* self, QueueWork* work) +{ + for (;;) { + Entry entry{}; + { + const std::lock_guard guard(work->mutex); + if (work->waiting.empty()) break; + entry = std::move(work->waiting.front()); + work->waiting.pop_front(); + } + fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value); + } +} + // Submit: entries that could not be stored fail now; waiting entries go to the worker, which is // started if it is not running yet (resources may have recovered since Enqueue). If it still cannot -// be started, the waiting entries fail too: their status entries and fences complete here, not -// earlier in Enqueue. +// be started, or the worker's list cannot grow, the waiting entries fail too: their status entries +// and fences complete here, not earlier in Enqueue. No exception leaves Submit. void submit(Object* self) { QueueWork* work = ensure_work(self); @@ -787,28 +802,27 @@ void submit(Object* self) fail_unrecorded(self); if (!work) return; if (!started) { - for (;;) { - Entry entry{}; - { - const std::lock_guard guard(work->mutex); - if (work->waiting.empty()) break; - entry = std::move(work->waiting.front()); - work->waiting.pop_front(); - } - fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value); - } + fail_waiting(self, work); return; } + bool all_moved = true; { const std::lock_guard guard(work->mutex); const u64 submission_id = ++work->next_submission_id; - for (auto& entry : work->waiting) { - entry.submission_id = submission_id; - work->submitted.push_back(std::move(entry)); + try { + // An entry leaves `waiting` only after it is in `submitted`, so a failed growth loses none. + while (!work->waiting.empty()) { + Entry& entry = work->waiting.front(); + entry.submission_id = submission_id; + work->submitted.push_back(std::move(entry)); + work->waiting.pop_front(); + } + } catch (const std::bad_alloc&) { + all_moved = false; } - work->waiting.clear(); } work->wake.notify_one(); + if (!all_moved) fail_waiting(self, work); } // Enqueue only records the entry, whether or not a worker runs; nothing completes before Submit. @@ -851,7 +865,12 @@ void __stdcall queue_enqueue_request(Object* self, const unsigned char* request) const unsigned page_offset = static_cast(*reinterpret_cast(request + 0x10) & 0xFFFF); const std::size_t pages = (std::size_t{page_offset} + destination_size + 0xFFFF) / 0x10000; if (title && pages && x2w_local::readable(title, pages * sizeof(ULONG_PTR))) { - entry.tokens.assign(title, title + pages); + try { + entry.tokens.assign(title, title + pages); + } catch (const std::bad_alloc&) { + defer_unrecorded(self, entry); // fails at Submit; nothing leaves Enqueue + return; + } for (ULONG_PTR token : entry.tokens) if (!token) InterlockedIncrement(&zero_tokens_at_enqueue); } diff --git a/tests/startup_storage_worker_start.cpp b/tests/startup_storage_worker_start.cpp index 4ceccab17..3cdf4e117 100644 --- a/tests/startup_storage_worker_start.cpp +++ b/tests/startup_storage_worker_start.cpp @@ -5,15 +5,19 @@ // of loading as a DLL, so it shares the test's allocator and CreateThread: // - CreateThread is redirected, for the stand-in's translation unit only, to a function that can // fail every thread creation (both the committed-stack attempt and the default-stack attempt); -// - operator new is replaced with one that throws std::bad_alloc on the calling thread when armed. -// The queue's three std::deque members allocate in their constructors, so the construction of -// the queue's work throws although the work itself is allocated with new (std::nothrow). +// - operator new is replaced with one that, when armed with N, throws std::bad_alloc from the N-th +// throwing-form allocation on the calling thread and then disarms itself, so exactly one +// allocation fails and everything after it (logging, library internals, recovery) behaves +// normally. Which allocation that is differs between standard libraries (a std::deque allocates +// in its constructor on some and at its first push_back on others), so the test sweeps N. // // Checks, each on a fresh queue: with no worker, before Submit the status entry is still pending, the // fence is not signaled and the destination is untouched; after Submit the status entry holds a -// failure and the fence is signaled; with a throwing queue construction no exception reaches the caller -// and the same holds; and once the failure is gone a request on the same queue returns correct data. -// A worker that cannot start at Enqueue but can at Submit runs the entries normally. +// failure and the fence is signaled. A worker that cannot start at Enqueue but can at Submit runs the +// entries normally. For every N at Enqueue and every N at Submit no exception reaches the caller, +// nothing completes inside Enqueue, and afterwards the request either completed with correct data or +// completed with a failure, the fence was signaled exactly once, and a later request on the same queue +// returns correct data. A crash or an unhandled exception names the stage it happened in. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -25,14 +29,16 @@ #include #include #include +#include #include +#include #include #include namespace { std::atomic fail_thread_creation{false}; std::atomic thread_attempts{0}; -thread_local bool throw_on_new = false; +thread_local int fail_countdown = 0; // 0: disarmed; N: the N-th throwing-form allocation throws std::atomic thrown{0}; HANDLE WINAPI creator_under_test(LPSECURITY_ATTRIBUTES attributes, SIZE_T stack, LPTHREAD_START_ROUTINE start, @@ -49,7 +55,7 @@ HANDLE WINAPI creator_under_test(LPSECURITY_ATTRIBUTES attributes, SIZE_T stack, void* operator new(std::size_t size) { - if (throw_on_new) { + if (fail_countdown > 0 && --fail_countdown == 0) { ++thrown; throw std::bad_alloc(); } @@ -199,19 +205,21 @@ bool untouched_bytes(const std::vector& bytes) return true; } -// A request, a status entry and a fence signal are enqueued; nothing may complete until Submit. -// before_enqueue / before_submit let the caller arm a failure around each step. -template -bool enqueue_without_effects(Fixture& f, Fixture::Queue& q, std::vector& destination, Arm arm) +// Requests, a status entry and a fence signal are enqueued; nothing may complete until Submit. Enough +// requests are enqueued to cross a block boundary of the queue's lists. fail_nth arms the N-th +// allocation to fail during the whole sequence (0: none). +constexpr int requests_per_run = 4; + +bool enqueue_without_effects(Fixture& f, Fixture::Queue& q, std::vector& destination, int fail_nth) { try { - arm(true); - f.request(q, destination); + fail_countdown = fail_nth; + for (int i = 0; i < requests_per_run; ++i) f.request(q, destination); f.status_entry(q, 0); f.signal(q, 7); - arm(false); + fail_countdown = 0; } catch (...) { - arm(false); + fail_countdown = 0; return fail("an exception left an Enqueue call"); } if (f.complete(q, 0) || f.hresult(q, 0) != pending_status) return fail("the status entry completed inside Enqueue"); @@ -246,7 +254,7 @@ bool worker_cannot_start(Fixture& f) std::vector destination(f.plain.size(), untouched); fail_thread_creation = true; thread_attempts = 0; - const bool effects_deferred = enqueue_without_effects(f, q, destination, [](bool) {}); + const bool effects_deferred = enqueue_without_effects(f, q, destination, 0); const int attempts = thread_attempts; f.submit(q); fail_thread_creation = false; @@ -264,7 +272,7 @@ bool worker_starts_at_submit(Fixture& f) if (!f.create(q, f.vtables)) return fail("cannot create the queue"); std::vector destination(f.plain.size(), untouched); fail_thread_creation = true; - const bool effects_deferred = enqueue_without_effects(f, q, destination, [](bool) {}); + const bool effects_deferred = enqueue_without_effects(f, q, destination, 0); fail_thread_creation = false; if (!effects_deferred) return false; f.submit(q); @@ -275,33 +283,141 @@ bool worker_starts_at_submit(Fixture& f) return true; } -// Constructing the queue's work throws std::bad_alloc, at Enqueue and also at Submit. -bool construction_throws(Fixture& f, bool throw_at_submit) +// One allocation fails at Enqueue (the fail_enqueue-th) and one at Submit (the fail_submit-th); 0 means +// none. A later request completing means every earlier entry has run or failed, since the worker runs +// entries in order and failures are completed inside Submit. +bool one_allocation_fails(Fixture& f, int fail_enqueue, int fail_submit, int& thrown_at_enqueue, int& thrown_at_submit) { Fixture::Queue q; if (!f.create(q, f.vtables)) return fail("cannot create the queue"); std::vector destination(f.plain.size(), untouched); thrown = 0; - const bool effects_deferred = enqueue_without_effects(f, q, destination, [](bool on) { throw_on_new = on; }); - if (!effects_deferred) return false; - if (thrown == 0) return fail("the queue construction never threw: the control did not reach the deques"); + if (!enqueue_without_effects(f, q, destination, fail_enqueue)) return false; + thrown_at_enqueue += thrown; + thrown = 0; try { - throw_on_new = throw_at_submit; + fail_countdown = fail_submit; f.submit(q); - throw_on_new = false; + fail_countdown = 0; } catch (...) { - throw_on_new = false; + fail_countdown = 0; return fail("an exception left Submit"); } - if (!failed_at_submit(f, q)) return false; - if (!untouched_bytes(destination)) return fail("the failed request changed its destination"); - return serves_next_request(f, q); + thrown_at_submit += thrown; + if (!serves_next_request(f, q)) return false; + if (!f.complete(q, 0)) return fail("the status entry stayed pending after later work completed"); + if (f.hresult(q, 0) == 0) { + if (destination != f.plain) return fail("a successful status entry has no data"); + } else if (f.hresult(q, 0) > 0 || (!untouched_bytes(destination) && destination != f.plain)) { + return fail("a failed request left partial data or a success-like status"); + } + if (q.fence.signals != 1 || q.fence.value != 7) return fail("the fence was not signaled exactly once"); + return true; +} + +// Every allocation point of Enqueue and of Submit is failed once, alone and in combination. +bool every_allocation_can_fail(Fixture& f) +{ + constexpr int sweep = 10; + int thrown_at_enqueue = 0, thrown_at_submit = 0; + for (int at_enqueue = 0; at_enqueue <= sweep; ++at_enqueue) + for (int at_submit = 0; at_submit <= sweep; ++at_submit) + if (!one_allocation_fails(f, at_enqueue, at_submit, thrown_at_enqueue, thrown_at_submit)) { + std::fprintf(stderr, " (allocation %d at Enqueue, allocation %d at Submit)\n", at_enqueue, at_submit); + return false; + } + if (thrown_at_enqueue == 0 || thrown_at_submit == 0) + return fail("the control never failed an allocation: the sweep did not reach the queue's storage"); + std::printf("allocation sweep: %d failures at Enqueue, %d at Submit\n", thrown_at_enqueue, thrown_at_submit); + return true; +} + +// A request with page tokens copies them into a vector at Enqueue: that allocation may fail too. +bool page_tokens_allocation_fails(Fixture& f) +{ + static ULONG_PTR title[1] = {0x10000}; + for (int fail_nth = 1; fail_nth <= 10; ++fail_nth) { + Fixture::Queue q; + if (!f.create(q, f.vtables)) return fail("cannot create the queue"); + unsigned char bytes[0x48] = {}; + *reinterpret_cast(bytes + 0x00) = 1 | (1ull << 21); + *reinterpret_cast(bytes + 0x08) = title; + *reinterpret_cast(bytes + 0x18) = 16; + try { + fail_countdown = fail_nth; + reinterpret_cast(q.queue->vtable[3])(q.queue, bytes); + f.status_entry(q, 0); + fail_countdown = 0; + } catch (...) { + fail_countdown = 0; + return fail("an exception left EnqueueRequest with page tokens"); + } + if (f.complete(q, 0)) return fail("the status entry completed inside Enqueue"); + } + return true; +} + +// A crash is never silent: whatever ends the process names the stage it was in. +const char* volatile current_stage = "start"; + +void report_end(const char* what, unsigned long code) +{ + std::fprintf(stderr, "FAIL: %s (0x%08lx) during stage \"%s\"\n", what, code, current_stage); + std::fflush(stderr); +} + +[[noreturn]] void on_terminate() +{ + report_end("std::terminate", 0); + std::_Exit(1); +} + +void on_abort(int) +{ + report_end("abort", 0); + std::_Exit(1); +} + +LONG WINAPI on_unhandled(EXCEPTION_POINTERS* info) +{ + report_end("unhandled exception", info && info->ExceptionRecord ? info->ExceptionRecord->ExceptionCode : 0); + TerminateProcess(GetCurrentProcess(), 1); + return EXCEPTION_EXECUTE_HANDLER; +} + +#ifdef _MSC_VER +void on_invalid_parameter(const wchar_t*, const wchar_t*, const wchar_t*, unsigned, std::uintptr_t) +{ + report_end("invalid parameter", 0); + std::_Exit(1); +} +#endif + +void install_crash_reports() +{ + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); + std::set_terminate(on_terminate); + std::signal(SIGABRT, on_abort); + SetUnhandledExceptionFilter(on_unhandled); +#ifdef _MSC_VER + _set_invalid_parameter_handler(on_invalid_parameter); + _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); +#endif +} + +bool stage(const char* name, bool (*run)(Fixture&), Fixture& f) +{ + current_stage = name; + std::fprintf(stderr, "stage: %s\n", name); + std::fflush(stderr); + return run(f); } } // namespace int main() { + install_crash_reports(); void* factory = nullptr; if (DStorageGetFactory(nullptr, &factory) != 0 || !factory) return fail("cannot get the factory"), 1; Fixture f; @@ -310,10 +426,10 @@ int main() for (std::size_t i = 0; i < f.plain.size(); ++i) f.plain[i] = static_cast((i % 251) ^ 0x5a); f.stream = stored_zlib(f.plain); - if (!worker_cannot_start(f)) return 1; - if (!worker_starts_at_submit(f)) return 1; - if (!construction_throws(f, false)) return 1; - if (!construction_throws(f, true)) return 1; - std::puts("a queue that cannot start its worker completes status and fences at Submit, and recovers"); + if (!stage("worker_cannot_start", worker_cannot_start, f)) return 1; + if (!stage("worker_starts_at_submit", worker_starts_at_submit, f)) return 1; + if (!stage("every_allocation_can_fail", every_allocation_can_fail, f)) return 1; + if (!stage("page_tokens_allocation_fails", page_tokens_allocation_fails, f)) return 1; + std::puts("a queue that cannot start its worker or allocate completes status and fences at Submit, and recovers"); return 0; } From f3e07e4985fb633ef8aad1555d5121f05816b3e6 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:40:53 +0100 Subject: [PATCH 090/775] runtime: keep the DirectStorage queue entry free of allocating moves and trace the allocation sweep Entry held its page tokens in a std::vector. In MSVC debug iterator mode a vector's default and move constructors allocate a container proxy, and Entry's implicit constructors and moves are noexcept, so one failed allocation inside Enqueue (Entry{}, push_back(std::move)) or Submit (the move to the submitted list, fail_waiting) ended in std::terminate. The tokens are now a unique_ptr array allocated with new (std::nothrow); a null result takes the existing unrecorded path. The test names every sweep step on stderr, adds a sweep that fails the N-th allocation of any thread while the worker is held off, and its crash handlers print thread, countdowns, the in-flight exception and a module+offset stack. --- src/startup_stubs/xcrdapi.cpp | 41 ++++--- tests/startup_storage_worker_start.cpp | 145 ++++++++++++++++++++++--- 2 files changed, 156 insertions(+), 30 deletions(-) diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 1f163ed93..1edb59161 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -60,10 +61,17 @@ struct Object { // tokens), a status entry or a fence signal. Entries run in order on the queue's worker after Submit, // like DirectStorage; a destination page token that was 0 at enqueue is read again at the entry's turn // (titles fill those in after EnqueueRequest). +// +// An Entry is default-constructed, moved and move-assigned on the Enqueue/Submit path, where an +// allocation may fail and nothing may escape. Those operations are implicitly noexcept, so no member +// may allocate in them: std::vector does in MSVC's debug iterator mode (its default and move +// constructors allocate a container proxy), and a bad_alloc there is std::terminate. The page tokens +// are therefore a plain array, allocated once with new (std::nothrow) at EnqueueRequest. struct Entry { enum Type { request, status_entry, signal } type; unsigned char bytes[0x48]; - std::vector tokens; + std::unique_ptr tokens; + std::size_t token_count = 0; Object* array; unsigned index; void* fence; @@ -569,31 +577,32 @@ void run_entry(Object* self, Entry& entry) { if (entry.type == Entry::request) { const u64 options = *reinterpret_cast(entry.bytes); - if ((options & (1ull << 21)) && !entry.tokens.empty()) { + if ((options & (1ull << 21)) && entry.token_count) { const auto* title = *reinterpret_cast(entry.bytes + 0x08); // The title's page array is read again in full when the request runs: entries are filled, // and also replaced, after enqueue. Writing through a token captured at enqueue put data // into a page the title had already reassigned. The caller has to keep the array readable // until the request runs; if it is not, the request fails before any page is written, so // no token captured at enqueue is ever used. - const std::size_t bytes = entry.tokens.size() * sizeof(ULONG_PTR); + const std::size_t bytes = entry.token_count * sizeof(ULONG_PTR); if (!title || !x2w_local::readable(title, bytes)) { InterlockedIncrement(&requests_failed); if (self) InterlockedExchange(&self->pending, static_cast(E_FAIL)); static LONG unreadable; if (InterlockedIncrement(&unreadable) <= 12) log("x2w-dstorage options=0x%llx page array %p (%zu entries) unreadable when the request runs -> failed", options, - static_cast(title), entry.tokens.size()); + static_cast(title), entry.token_count); return; } - std::vector now(title, title + entry.tokens.size()); // one snapshot of the whole array - for (std::size_t i = 0; i < now.size(); ++i) { - if (entry.tokens[i] && now[i] != entry.tokens[i]) InterlockedIncrement(&tokens_replaced_after_enqueue); - if (!now[i]) InterlockedIncrement(&zero_tokens_at_run); + // Overwrite in place: the queue entry is kept free of allocations on this path. + for (std::size_t i = 0; i < entry.token_count; ++i) { + const ULONG_PTR now = title[i]; + if (entry.tokens[i] && now != entry.tokens[i]) InterlockedIncrement(&tokens_replaced_after_enqueue); + if (!now) InterlockedIncrement(&zero_tokens_at_run); + entry.tokens[i] = now; } - entry.tokens = std::move(now); } - execute_request(self, entry.bytes, entry.tokens.empty() ? nullptr : entry.tokens.data(), entry.id, entry.submission_id); + execute_request(self, entry.bytes, entry.token_count ? entry.tokens.get() : nullptr, entry.id, entry.submission_id); } else if (entry.type == Entry::status_entry) { const LONG result = InterlockedExchange(&self->pending, S_OK); InterlockedExchange(&entry.array->results[entry.index], result); @@ -865,14 +874,16 @@ void __stdcall queue_enqueue_request(Object* self, const unsigned char* request) const unsigned page_offset = static_cast(*reinterpret_cast(request + 0x10) & 0xFFFF); const std::size_t pages = (std::size_t{page_offset} + destination_size + 0xFFFF) / 0x10000; if (title && pages && x2w_local::readable(title, pages * sizeof(ULONG_PTR))) { - try { - entry.tokens.assign(title, title + pages); - } catch (const std::bad_alloc&) { + entry.tokens.reset(new (std::nothrow) ULONG_PTR[pages]); + if (!entry.tokens) { defer_unrecorded(self, entry); // fails at Submit; nothing leaves Enqueue return; } - for (ULONG_PTR token : entry.tokens) - if (!token) InterlockedIncrement(&zero_tokens_at_enqueue); + entry.token_count = pages; + for (std::size_t i = 0; i < pages; ++i) { + entry.tokens[i] = title[i]; + if (!title[i]) InterlockedIncrement(&zero_tokens_at_enqueue); + } } } push(self, std::move(entry)); diff --git a/tests/startup_storage_worker_start.cpp b/tests/startup_storage_worker_start.cpp index 3cdf4e117..35450e3bd 100644 --- a/tests/startup_storage_worker_start.cpp +++ b/tests/startup_storage_worker_start.cpp @@ -33,13 +33,28 @@ #include #include #include +#include #include namespace { std::atomic fail_thread_creation{false}; std::atomic thread_attempts{0}; thread_local int fail_countdown = 0; // 0: disarmed; N: the N-th throwing-form allocation throws +std::atomic global_countdown{0}; // same, counted over every thread of the process +bool sweep_all_threads = false; // which of the two countdowns arm() sets std::atomic thrown{0}; +DWORD main_thread_id = 0; + +void arm(int nth) +{ + if (sweep_all_threads) global_countdown = nth; + else fail_countdown = nth; +} +void disarm() +{ + fail_countdown = 0; + global_countdown = 0; +} HANDLE WINAPI creator_under_test(LPSECURITY_ATTRIBUTES attributes, SIZE_T stack, LPTHREAD_START_ROUTINE start, LPVOID parameter, DWORD flags, LPDWORD id) @@ -59,6 +74,10 @@ void* operator new(std::size_t size) ++thrown; throw std::bad_alloc(); } + if (global_countdown.load(std::memory_order_relaxed) > 0 && global_countdown.fetch_sub(1) == 1) { + ++thrown; + throw std::bad_alloc(); + } if (void* memory = std::malloc(size ? size : 1)) return memory; throw std::bad_alloc(); } @@ -210,18 +229,41 @@ bool untouched_bytes(const std::vector& bytes) // allocation to fail during the whole sequence (0: none). constexpr int requests_per_run = 4; +// Every step of a sweep names itself on stderr before it runs, so the last line before a crash names +// the exact sweep, allocation number and call. +const char* sweep_name = "none"; +int sweep_n = 0, sweep_m = 0; +void trace(const char* step, int index = -1) +{ + if (index >= 0) + std::fprintf(stderr, "sweep=%s N=%d submit_N=%d all_threads=%d step=%s #%d\n", sweep_name, sweep_n, sweep_m, + sweep_all_threads ? 1 : 0, step, index); + else + std::fprintf(stderr, "sweep=%s N=%d submit_N=%d all_threads=%d step=%s\n", sweep_name, sweep_n, sweep_m, + sweep_all_threads ? 1 : 0, step); + std::fflush(stderr); +} + bool enqueue_without_effects(Fixture& f, Fixture::Queue& q, std::vector& destination, int fail_nth) { try { - fail_countdown = fail_nth; - for (int i = 0; i < requests_per_run; ++i) f.request(q, destination); + trace("arm_enqueue"); + arm(fail_nth); + for (int i = 0; i < requests_per_run; ++i) { + trace("enqueue_request", i + 1); + f.request(q, destination); + } + trace("enqueue_status"); f.status_entry(q, 0); + trace("enqueue_signal"); f.signal(q, 7); - fail_countdown = 0; + disarm(); + trace("enqueue_done"); } catch (...) { - fail_countdown = 0; + disarm(); return fail("an exception left an Enqueue call"); } + trace("check_enqueue"); if (f.complete(q, 0) || f.hresult(q, 0) != pending_status) return fail("the status entry completed inside Enqueue"); if (q.fence.signals != 0 || q.fence.value != 0) return fail("the fence was signaled inside Enqueue"); if (!untouched_bytes(destination)) return fail("the destination changed inside Enqueue"); @@ -288,23 +330,36 @@ bool worker_starts_at_submit(Fixture& f) // entries in order and failures are completed inside Submit. bool one_allocation_fails(Fixture& f, int fail_enqueue, int fail_submit, int& thrown_at_enqueue, int& thrown_at_submit) { + sweep_n = fail_enqueue; + sweep_m = fail_submit; + sweep_name = fail_submit == 0 ? "enqueue" : fail_enqueue == 0 ? "submit" : "both"; + trace("create"); Fixture::Queue q; if (!f.create(q, f.vtables)) return fail("cannot create the queue"); std::vector destination(f.plain.size(), untouched); thrown = 0; - if (!enqueue_without_effects(f, q, destination, fail_enqueue)) return false; + // On every thread, the queue's worker must not run during Enqueue, or its own allocations would + // be counted: the creator hook holds it off until Submit. + fail_thread_creation = sweep_all_threads; + const bool enqueued = enqueue_without_effects(f, q, destination, fail_enqueue); + fail_thread_creation = false; + if (!enqueued) return false; thrown_at_enqueue += thrown; thrown = 0; try { - fail_countdown = fail_submit; + trace("submit"); + arm(fail_submit); f.submit(q); - fail_countdown = 0; + disarm(); + trace("submit_done"); } catch (...) { - fail_countdown = 0; + disarm(); return fail("an exception left Submit"); } thrown_at_submit += thrown; + trace("serve_next_request"); if (!serves_next_request(f, q)) return false; + trace("check_result"); if (!f.complete(q, 0)) return fail("the status entry stayed pending after later work completed"); if (f.hresult(q, 0) == 0) { if (destination != f.plain) return fail("a successful status entry has no data"); @@ -315,10 +370,12 @@ bool one_allocation_fails(Fixture& f, int fail_enqueue, int fail_submit, int& th return true; } -// Every allocation point of Enqueue and of Submit is failed once, alone and in combination. -bool every_allocation_can_fail(Fixture& f) +// Every allocation point of Enqueue and of Submit is failed once, alone and in combination. The +// first stage fails allocations of the calling thread only; the second counts allocations of every +// thread of the process (the queue's worker included once Submit starts it). +bool allocation_sweep(Fixture& f, int sweep, bool all_threads) { - constexpr int sweep = 10; + sweep_all_threads = all_threads; int thrown_at_enqueue = 0, thrown_at_submit = 0; for (int at_enqueue = 0; at_enqueue <= sweep; ++at_enqueue) for (int at_submit = 0; at_submit <= sweep; ++at_submit) @@ -328,15 +385,24 @@ bool every_allocation_can_fail(Fixture& f) } if (thrown_at_enqueue == 0 || thrown_at_submit == 0) return fail("the control never failed an allocation: the sweep did not reach the queue's storage"); - std::printf("allocation sweep: %d failures at Enqueue, %d at Submit\n", thrown_at_enqueue, thrown_at_submit); + std::printf("allocation sweep (%s): %d failures at Enqueue, %d at Submit\n", all_threads ? "all threads" : "main thread", + thrown_at_enqueue, thrown_at_submit); + sweep_all_threads = false; return true; } +bool every_allocation_can_fail(Fixture& f) { return allocation_sweep(f, 10, false); } +bool every_allocation_on_every_thread_can_fail(Fixture& f) { return allocation_sweep(f, 12, true); } + // A request with page tokens copies them into a vector at Enqueue: that allocation may fail too. bool page_tokens_allocation_fails(Fixture& f) { static ULONG_PTR title[1] = {0x10000}; + sweep_name = "tokens"; + sweep_m = 0; for (int fail_nth = 1; fail_nth <= 10; ++fail_nth) { + sweep_n = fail_nth; + trace("create"); Fixture::Queue q; if (!f.create(q, f.vtables)) return fail("cannot create the queue"); unsigned char bytes[0x48] = {}; @@ -344,12 +410,15 @@ bool page_tokens_allocation_fails(Fixture& f) *reinterpret_cast(bytes + 0x08) = title; *reinterpret_cast(bytes + 0x18) = 16; try { - fail_countdown = fail_nth; + trace("arm_enqueue"); + arm(fail_nth); + trace("enqueue_request", 1); reinterpret_cast(q.queue->vtable[3])(q.queue, bytes); + trace("enqueue_status"); f.status_entry(q, 0); - fail_countdown = 0; + disarm(); } catch (...) { - fail_countdown = 0; + disarm(); return fail("an exception left EnqueueRequest with page tokens"); } if (f.complete(q, 0)) return fail("the status entry completed inside Enqueue"); @@ -360,9 +429,53 @@ bool page_tokens_allocation_fails(Fixture& f) // A crash is never silent: whatever ends the process names the stage it was in. const char* volatile current_stage = "start"; +// Nothing here allocates: fixed buffers and fprintf only, and both countdowns are disarmed first. +void print_frame(const void* address) +{ + HMODULE module = nullptr; + char path[MAX_PATH] = "?"; + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(address), &module) && + module) { + const DWORD length = GetModuleFileNameA(module, path, MAX_PATH); + if (length == 0 || length >= MAX_PATH) std::snprintf(path, sizeof path, "?"); + const char* name = path; + for (const char* p = path; *p; ++p) + if (*p == '\\' || *p == '/') name = p + 1; + std::fprintf(stderr, " %s+0x%llx\n", name, + static_cast(static_cast(address) - reinterpret_cast(module))); + } else { + std::fprintf(stderr, " %p\n", address); + } +} + void report_end(const char* what, unsigned long code) { + const int armed_here = fail_countdown; + const int armed_global = global_countdown.load(); + disarm(); std::fprintf(stderr, "FAIL: %s (0x%08lx) during stage \"%s\"\n", what, code, current_stage); + std::fprintf(stderr, " last sweep=%s N=%d submit_N=%d all_threads=%d\n", sweep_name, sweep_n, sweep_m, + sweep_all_threads ? 1 : 0); + std::fprintf(stderr, " thread=%lu main_thread=%lu on_main=%d countdown_this_thread=%d countdown_global=%d thrown=%d\n", + GetCurrentThreadId(), main_thread_id, GetCurrentThreadId() == main_thread_id ? 1 : 0, armed_here, + armed_global, thrown.load()); + std::exception_ptr in_flight = std::current_exception(); + if (!in_flight) { + std::fprintf(stderr, " no in-flight exception: noexcept/destructor/thread-entry/rethrow-without-active\n"); + } else { + try { + std::rethrow_exception(in_flight); + } catch (const std::exception& error) { + std::fprintf(stderr, " in-flight exception: %s: %s\n", typeid(error).name(), error.what()); + } catch (...) { + std::fprintf(stderr, " in-flight exception: non-std exception\n"); + } + } + void* frames[32] = {}; + const USHORT count = RtlCaptureStackBackTrace(0, 32, frames, nullptr); + std::fprintf(stderr, " stack (%u frames, module+offset):\n", static_cast(count)); + for (USHORT i = 0; i < count; ++i) print_frame(frames[i]); std::fflush(stderr); } @@ -417,6 +530,7 @@ bool stage(const char* name, bool (*run)(Fixture&), Fixture& f) int main() { + main_thread_id = GetCurrentThreadId(); install_crash_reports(); void* factory = nullptr; if (DStorageGetFactory(nullptr, &factory) != 0 || !factory) return fail("cannot get the factory"), 1; @@ -429,6 +543,7 @@ int main() if (!stage("worker_cannot_start", worker_cannot_start, f)) return 1; if (!stage("worker_starts_at_submit", worker_starts_at_submit, f)) return 1; if (!stage("every_allocation_can_fail", every_allocation_can_fail, f)) return 1; + if (!stage("every_allocation_on_every_thread_can_fail", every_allocation_on_every_thread_can_fail, f)) return 1; if (!stage("page_tokens_allocation_fails", page_tokens_allocation_fails, f)) return 1; std::puts("a queue that cannot start its worker or allocate completes status and fences at Submit, and recovers"); return 0; From f80e341b1ce8ece9425fe79ac6f4895df5df4d23 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:52:42 +0100 Subject: [PATCH 091/775] runtime: keep DirectStorage queue entries in order when an allocation fails during Enqueue --- docs/startup-runtime.md | 13 ++- src/startup_stubs/xcrdapi.cpp | 43 +++++++-- tests/startup_storage_worker_start.cpp | 123 +++++++++++++++++++++++++ 3 files changed, 168 insertions(+), 11 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index b0bbaba94..bb090ff24 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -424,11 +424,22 @@ These are measured on one executable; treat them as hypotheses for others. the small record itself cannot be allocated is the entry failed inside Enqueue. No exception leaves Enqueue or Submit: a request whose page tokens cannot be copied is recorded the same way, and if Submit cannot grow the worker's list the entries still waiting fail there. + Entry order is kept: once an entry has been deferred, every later entry until the next Submit is + deferred too, so the stored entries are an in-order prefix and the deferred ones the in-order + suffix. Submit handles the prefix first (worker or failure), then fails the suffix, so a failure + reaches the next status entry after it and never stays pending behind a status entry that + completed. Limits: when the prefix runs on the worker, a suffix status entry fails synchronously + inside Submit and cannot see a failure the worker finds later in the prefix (a later status entry + will); after the first allocation failure the rest of the batch fails with `E_OUTOFMEMORY` even if + memory recovered, which is preferable to reordering. `startup_storage_worker_start` compiles the stand-in into the test, redirects `CreateThread` and replaces `operator new` with one that fails the N-th allocation once and then behaves normally. It sweeps N over Enqueue and Submit, and checks pending status and an unsignaled fence before Submit, then a request that completed with correct data or a failure, a fence signaled - once, and a correct request on the same queue afterwards. A crash names the stage it was in. + once, and a correct request on the same queue afterwards. A second control fails the N-th allocation + of Enqueue and the M-th of Submit for 1 to 9 requests with the status entry before or after them + and checks that a failure is reported by one status entry only and that a later clean request and + status entry complete correctly. A crash names the stage it was in. ## Shortcuts that are known to be wrong diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 1edb59161..a444fdd63 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -756,7 +756,25 @@ void fail_unstarted(Object* self, Entry::Type type, Object* array, unsigned inde // An entry the queue has no room for (its work could not be built or grown): remembered in a small // record that needs no queue storage, failed by the next Submit. Only when even that record cannot be -// allocated is the entry failed here, because nothing is left to remember it with. +// allocated is the entry failed here, because nothing is left to remember it with (a documented last +// resort: that entry may then be failed ahead of the ones stored before it). +// +// Order. One accumulator (Object::pending) holds the worst failure since the previous status entry, +// and a status entry consumes it, so an entry that lost its place in the queue order would leak a +// failure past the status entry it belongs to. Therefore, once an entry of this queue has been +// deferred, every later entry until the next Submit is deferred too, even if it could be stored: +// the stored entries (`waiting`) are an in-order prefix and the deferred ones an in-order suffix. +// Submit handles the prefix first (moves it to the worker, or fails it), then fails the suffix. +// Limitation: when the prefix runs on the worker, a status entry in the suffix fails synchronously +// inside Submit and cannot see a failure the worker finds later in the prefix; the next status entry +// will. After the first allocation failure the rest of the batch fails with E_OUTOFMEMORY even if +// memory has recovered, which is acceptable under out-of-memory and preferable to reordering. +bool has_unrecorded(Object* self) +{ + const std::lock_guard guard(setup_mutex()); + return self->unrecorded_head != nullptr; +} + void defer_unrecorded(Object* self, const Entry& entry) { auto* node = new (std::nothrow) Unrecorded{nullptr, entry.type, entry.array, entry.index, entry.fence, entry.value}; @@ -800,18 +818,22 @@ void fail_waiting(Object* self, QueueWork* work) } } -// Submit: entries that could not be stored fail now; waiting entries go to the worker, which is -// started if it is not running yet (resources may have recovered since Enqueue). If it still cannot -// be started, or the worker's list cannot grow, the waiting entries fail too: their status entries -// and fences complete here, not earlier in Enqueue. No exception leaves Submit. +// Submit: waiting entries (the in-order prefix) go to the worker, which is started if it is not +// running yet (resources may have recovered since Enqueue). If it still cannot be started, or the +// worker's list cannot grow, the waiting entries fail. Only then do the entries that could not be +// stored (the in-order suffix, see defer_unrecorded) fail, so every failure reaches the status entry +// after it, in order. Their status entries and fences complete here, not earlier in Enqueue. No +// exception leaves Submit. void submit(Object* self) { QueueWork* work = ensure_work(self); - const bool started = work && start_worker(self, work); - fail_unrecorded(self); - if (!work) return; - if (!started) { + if (!work) { + fail_unrecorded(self); + return; + } + if (!start_worker(self, work)) { fail_waiting(self, work); + fail_unrecorded(self); return; } bool all_moved = true; @@ -832,13 +854,14 @@ void submit(Object* self) } work->wake.notify_one(); if (!all_moved) fail_waiting(self, work); + fail_unrecorded(self); } // Enqueue only records the entry, whether or not a worker runs; nothing completes before Submit. void push(Object* self, Entry&& entry) { QueueWork* work = ensure_work(self); - if (!work) { + if (!work || has_unrecorded(self)) { // after a deferred entry every later one is deferred: order defer_unrecorded(self, entry); return; } diff --git a/tests/startup_storage_worker_start.cpp b/tests/startup_storage_worker_start.cpp index 35450e3bd..c46c4b101 100644 --- a/tests/startup_storage_worker_start.cpp +++ b/tests/startup_storage_worker_start.cpp @@ -426,6 +426,128 @@ bool page_tokens_allocation_fails(Fixture& f) return true; } +// The entries of one queue keep their order when an allocation fails in the middle of Enqueue: the +// failure of an entry must reach the next status entry after it and no other. A control enqueues +// requests, a status entry and a fence signal (status_first: the status entry before the requests), +// fails the N-th allocation of Enqueue and the M-th of Submit, and checks what a caller can see: +// - nothing completes inside Enqueue, no exception leaves Enqueue or Submit; +// - status 0 and the fence complete (the fence exactly once) and no destination holds partial data; +// - a clean request plus status 1 afterwards completes with the right bytes, and with S_OK when +// every failure came before status 0 (requests first); with the status entry first a request lost +// after it is reported once, by status 1, and +// - a second clean request plus status 2 completes with S_OK: a failure is reported by one status +// entry only and never stays pending behind it. +// The number of requests is swept too, because the standard libraries differ in which entry needs a +// new block of the queue's list. This is not a speculative sweep: for the old code, in which an entry +// that could not be stored was failed at Submit before the entries that were stored, some (N, M, +// requests) triple leaves a failure behind a status entry that already completed. +constexpr int max_ordered_requests = 9; + +struct CleanRound { + bool completed = false; + long result = -1; + bool data = false; +}; + +CleanRound clean_round(Fixture& f, Fixture::Queue& q, unsigned index) +{ + CleanRound round; + std::vector destination(f.plain.size(), untouched); + f.request(q, destination); + f.status_entry(q, index); + f.submit(q); + round.completed = f.wait(q, index); + if (round.completed) { + round.result = f.hresult(q, index); + round.data = destination == f.plain; + } + return round; +} + +bool ordered_failure(Fixture& f, bool status_first, int requests, int fail_enqueue, int fail_submit) +{ + sweep_n = fail_enqueue; + sweep_m = fail_submit; + sweep_name = status_first ? "order_status_first" : "order_status_last"; + sweep_all_threads = false; + trace("create"); + Fixture::Queue q; + if (!f.create(q, f.vtables)) return fail("cannot create the queue"); + std::vector destination(f.plain.size(), untouched); + int failed_requests_at_enqueue = 0; + try { + trace("arm_enqueue"); + arm(fail_enqueue); + if (status_first) { + trace("enqueue_status"); + f.status_entry(q, 0); + } + for (int i = 0; i < requests; ++i) { + trace("enqueue_request", i + 1); + const int before = thrown; + f.request(q, destination); + failed_requests_at_enqueue += thrown - before; + } + if (!status_first) { + trace("enqueue_status"); + f.status_entry(q, 0); + } + trace("enqueue_signal"); + f.signal(q, 7); + disarm(); + trace("enqueue_done"); + } catch (...) { + disarm(); + return fail("an exception left an Enqueue call"); + } + if (f.complete(q, 0) || f.hresult(q, 0) != pending_status) return fail("the status entry completed inside Enqueue"); + if (q.fence.signals != 0) return fail("the fence was signaled inside Enqueue"); + if (!untouched_bytes(destination)) return fail("the destination changed inside Enqueue"); + try { + trace("submit"); + arm(fail_submit); + f.submit(q); + disarm(); + trace("submit_done"); + } catch (...) { + disarm(); + return fail("an exception left Submit"); + } + trace("serve_next_request"); + const CleanRound first = clean_round(f, q, 1); + if (!first.completed) return fail("a request after the failure never completed"); + if (!first.data) return fail("a request after the failure returned wrong data"); + if (!status_first && first.result != 0) return fail("a failure that came before status 0 was reported again by status 1"); + trace("serve_second_request"); + const CleanRound second = clean_round(f, q, 2); + if (!second.completed) return fail("a second request after the failure never completed"); + if (second.result != 0 || !second.data) return fail("a failure stayed pending behind a status entry that had completed"); + trace("check_result"); + if (!f.complete(q, 0)) return fail("status 0 stayed pending after later work completed"); + if (f.hresult(q, 0) > 0 || (!untouched_bytes(destination) && destination != f.plain)) + return fail("a failed request left partial data or a success-like status"); + const DWORD start = GetTickCount(); + while (q.fence.signals == 0 && GetTickCount() - start < completion_timeout_ms) Sleep(5); + if (q.fence.signals != 1 || q.fence.value != 7) return fail("the fence was not signaled exactly once"); + return true; +} + +bool entries_keep_their_order(Fixture& f) +{ + int cases = 0; + for (int status_first = 0; status_first <= 1; ++status_first) + for (int requests = 1; requests <= max_ordered_requests; ++requests) + for (int at_enqueue = 1; at_enqueue <= 14; ++at_enqueue) + for (int at_submit = 0; at_submit <= 3; ++at_submit, ++cases) + if (!ordered_failure(f, status_first != 0, requests, at_enqueue, at_submit)) { + std::fprintf(stderr, " (%d requests, allocation %d at Enqueue, allocation %d at Submit)\n", requests, + at_enqueue, at_submit); + return false; + } + std::printf("entry order under allocation failure: %d cases\n", cases); + return true; +} + // A crash is never silent: whatever ends the process names the stage it was in. const char* volatile current_stage = "start"; @@ -545,6 +667,7 @@ int main() if (!stage("every_allocation_can_fail", every_allocation_can_fail, f)) return 1; if (!stage("every_allocation_on_every_thread_can_fail", every_allocation_on_every_thread_can_fail, f)) return 1; if (!stage("page_tokens_allocation_fails", page_tokens_allocation_fails, f)) return 1; + if (!stage("entries_keep_their_order", entries_keep_their_order, f)) return 1; std::puts("a queue that cannot start its worker or allocate completes status and fences at Submit, and recovers"); return 0; } From bf1b5b864729e064b73311b3dfd8fbcb1dd45078 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:14:14 +0100 Subject: [PATCH 092/775] triage_run: redact paths with spaces, de-duplicate mirrored stderr/trap logs, ignore successful forwarded slots --- tests/startup_triage_run_check.py | 41 +++++++++++++++++++++++++++++++ tools/startup/triage_run.py | 33 ++++++++++++++++++++++--- 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 49ef7f8ad..84ded3af9 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -109,6 +109,46 @@ def check_redaction_helper(failures: list[str]) -> None: failures.append(f"redact({raw!r}) = {got!r}, expected {want!r}") +def check_review_regressions(failures: list[str]) -> None: + # Paths with spaces are redacted whole, in a shader .fail line and in plain text. + for raw, want in [ + (r"fxc ps: C:\Users\Alice Smith\PrivateTitle\shader.hlsl(1,1): error X3000", + "fxc ps: error X3000"), + (r"open C:\Program Files\My App\shader.hlsl failed", "open failed"), + ("read /home/Alice Smith/cache/x.bin: denied", "read denied"), + ]: + got = triage_run.redact(raw) + if got != want or "Smith" in got or "Program" in got: + failures.append(f"redact({raw!r}) = {got!r}, expected {want!r}") + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "run" + logdir.mkdir() + fail_line = "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x0 size=0x100 -> zlib failed\n" + (logdir / "stderr.txt").write_text(fail_line, encoding="utf-8") + (logdir / "trap.log").write_text(fail_line, encoding="utf-8") + report = triage_run.triage_run(logdir) + if "| 1 | zlib failed |" not in report: + failures.append("mirrored stderr.txt/trap.log line counted other than once:\n" + report) + # A genuine repeat (second occurrence only in trap.log) still counts. + (logdir / "trap.log").write_text(fail_line * 2, encoding="utf-8") + report = triage_run.triage_run(logdir) + if "| 2 | zlib failed |" not in report: + failures.append("repeated trap.log occurrence beyond stderr.txt was dropped:\n" + report) + # Successful forwarded slots are not "unhandled"; failed ones and untraced calls still are. + lines = [ + "x2w-d3d12 Device::slot13(0x1, 0x2, 0x3, 0x4, 0x5) -> 0x0\n", + "x2w-d3d12 Device::slot41(0x1, 0x2, 0x3, 0x4, 0x5) -> 0x0\n", + "x2w-d3d12 Device::slot14(0x1, 0x2, 0x3, 0x4, 0x5) -> 0x80070057\n", + "x2w-d3d12 Device::slot15 not implemented\n", + ] + unhandled = triage_run.summarize_lines(lines)["d3d12_unhandled"] + if "Device::slot13" in unhandled or "Device::slot41" in unhandled: + failures.append(f"successful forwarded slots counted as unhandled: {dict(unhandled)}") + if "Device::slot14" not in unhandled or "Device::slot15" not in unhandled: + failures.append(f"failed/untraced slots missing from unhandled: {dict(unhandled)}") + + def check_empty_and_missing_dirs(failures: list[str]) -> None: with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) @@ -148,6 +188,7 @@ def main() -> int: failures: list[str] = [] check_aggregation_and_redaction(failures) check_redaction_helper(failures) + check_review_regressions(failures) check_empty_and_missing_dirs(failures) check_cli_invocation(failures) for item in failures: diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index c98344f4a..4d38561e7 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -31,12 +31,17 @@ # Redaction patterns (applied in order from most specific/broadest path to tokens). RE_QUOTED_WIN_PATH = re.compile(r'"([A-Za-z]:\\[^"\r\n]+|[A-Za-z]:/[^"\r\n]+|\\\\[^\\"\r\n]+\\[^"\r\n]+)"') -RE_WIN_PATH = re.compile(r'(?:[A-Za-z]:\\[^\s"\'<>|]+|[A-Za-z]:/[^\s"\'<>|]+|\\\\[^\s"\'<>|\\]+\\[^\s"\'<>|]+)') +# Unquoted paths: directory components may contain single spaces ("Alice Smith"), the final component may not. +_DIR_COMPONENT = r'(?:[^\\/:"\'<>|\r\n=,()]{1,64}[\\/]+)*' +_LAST_COMPONENT = r'[^\s"\'<>|]*' +RE_WIN_PATH = re.compile( + r'(?:[A-Za-z]:[\\/]+|\\\\[^\\\s"\'<>|]+\\+)' + _DIR_COMPONENT + _LAST_COMPONENT +) RE_QUOTED_POSIX_PATH = re.compile( r'"(/(?:home|Users|mnt|tmp|var|opt|root|srv|private|Volumes)/[^"\r\n]+)"' ) RE_POSIX_PATH = re.compile( - r'/(?:home|Users|mnt|tmp|var|opt|root|srv|private|Volumes)(?:/[^\s"\'<>|]+)+' + r'/(?:home|Users|mnt|tmp|var|opt|root|srv|private|Volumes)/' + _DIR_COMPONENT + r'[^\s"\'<>|]+' ) RE_EXE_NAME = re.compile(r'\b[A-Za-z0-9_.\-]+\.exe\b', re.IGNORECASE) RE_ADDR64 = re.compile(r'\b0x[0-9a-fA-F]{9,}\b') @@ -53,6 +58,7 @@ ) RE_D3D12_IID_PASS = re.compile(r'x2w-d3d12\s+Device::slot(\d+)\s+passes an IID:') RE_D3D12_VIEW_SKIPPED = re.compile(r'x2w-d3d12\s+Device::slot(\d+)\s+view skipped:\s+(.+)$') +RE_D3D12_FORWARDED_RESULT = re.compile(r'::slot\d+\(.*\)\s*->\s*(0x[0-9a-fA-F]+)\s*$') RE_D3D12_SLOT_CALL = re.compile(r'x2w-d3d12\s+([A-Za-z0-9_]+::slot\d+)\b') RE_D3D12_REMOVED = re.compile( r'x2w-d3d12\s+DEVICE REMOVED,\s+reason\s+(0x[0-9a-fA-F]+),\s+first noticed after\s+(.+)$' @@ -195,6 +201,9 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]: if m: d3d12_unhandled[f"Device::slot{m.group(1)} view skipped: {redact(m.group(2))}"] += 1 continue + m = RE_D3D12_FORWARDED_RESULT.search(line) + if m and not _is_failed_hresult(m.group(1))[0]: + continue # forward_slot()/create_slot() telemetry of a call the desktop device implemented m = RE_D3D12_SLOT_CALL.search(line) if m: d3d12_unhandled[m.group(1)] += 1 @@ -452,11 +461,29 @@ def triage_run( """Scan logdir (and optional shader_cache) and return a redacted Markdown summary.""" log_files = iter_log_files(logdir) + # run.ps1 / debug_launch.py capture stderr.txt while X2W_TRAP_LOG appends the same lines to trap.log: + # each trap.log line already present in the sibling stderr.txt is skipped once, so repeats still count. + mirrored: dict[Path, Counter[str]] = {} + for path in log_files: + if path.name.lower() == "trap.log" and (path.parent / "stderr.txt") in log_files: + seen: Counter[str] = Counter() + try: + with (path.parent / "stderr.txt").open("r", encoding="utf-8", errors="replace") as handle: + seen.update(line.rstrip("\r\n") for line in handle) + except OSError: + pass + mirrored[path] = seen + def _line_stream() -> Iterable[str]: for path in log_files: + budget = mirrored.get(path) try: with path.open("r", encoding="utf-8", errors="replace") as handle: - yield from handle + for line in handle: + if budget is not None and budget[line.rstrip("\r\n")] > 0: + budget[line.rstrip("\r\n")] -= 1 + continue + yield line except OSError: continue From 941510be1a4520c22215e396a09331f2fea3fb70 Mon Sep 17 00:00:00 2001 From: sydney-0o <215686885+sydney-0o@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:17:11 +0500 Subject: [PATCH 093/775] tooling: show startup storage and render summaries --- docs/startup-runtime.md | 8 +++++ tests/startup_live_view_check.py | 51 +++++++++++++++++++++++++------- tools/startup/live_view.py | 9 +++++- 3 files changed, 57 insertions(+), 11 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9ff8d97c1..1bfb15b32 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -588,6 +588,14 @@ write) until its grant is released; `xmem.dll` publishes that count through the `x2w_xmem_page_stats` export. The heartbeat also prints while the request counters are unchanged when either memory value changed, so the cost of a stalled load is visible. +The live log window also shows DirectStorage heartbeat lines and `x2w-render totals` as they +arrive. It reports frame counts and FPS from the graphics heartbeat without inferring whether +draws were executed. Network refusals are shown when observed; the window does not establish +that all network activity is blocked. To check this presentation with generated logs, run +`python -B tests/startup_live_view_check.py`. See [#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199) +for memory accounting and [#1281](https://github.com/R0Y00/Xbox2Windows/issues/1281) for +the launcher's concurrent-hook limitation. + ```powershell cmake --build --preset release --target xmem_shim startup_stub_xcrdapi ctest --preset release --no-tests=error -R '^(xmem_page_stats|startup_heartbeat_commit)$' -V diff --git a/tests/startup_live_view_check.py b/tests/startup_live_view_check.py index 0317788c9..7f4225852 100644 --- a/tests/startup_live_view_check.py +++ b/tests/startup_live_view_check.py @@ -1,4 +1,4 @@ -"""Check that the live viewer reports only what a frame heartbeat establishes.""" +"""Check the live viewer with generated startup log lines.""" import contextlib import io @@ -11,23 +11,54 @@ class LiveViewCheck(unittest.TestCase): - def test_frame_heartbeat_does_not_claim_draws_were_dropped(self): + def view_log(self, first_chunk, second_chunk=None): viewer = Path(__file__).resolve().parents[1] / "tools" / "startup" / "live_view.py" with tempfile.TemporaryDirectory() as directory: root = Path(directory) - (root / "trap.log").write_text( - "x2w-d3d12 heartbeat: 60 frames presented in 2.0 s (30.0 fps overall)\n", - encoding="utf-8", - ) - (root / "finished.txt").write_text("finished\n", encoding="utf-8") + log = root / "trap.log" + log.write_text(first_chunk, encoding="utf-8") + finished = root / "finished.txt" + + def finish_run(_seconds): + if not finished.exists(): + if second_chunk is not None: + with log.open("a", encoding="utf-8", newline="\n") as handle: + handle.write(second_chunk) + finished.write_text("finished\n", encoding="utf-8") + + if second_chunk is None: + finish_run(0) output = io.StringIO() with mock.patch.object(sys, "argv", [str(viewer), directory]), \ - mock.patch("os.system"), mock.patch("time.sleep"), \ + mock.patch("os.system"), mock.patch("time.sleep", side_effect=finish_run), \ contextlib.redirect_stdout(output): runpy.run_path(str(viewer), run_name="__main__") + return output.getvalue() + + def test_frame_heartbeat_does_not_claim_draws_were_dropped(self): + output = self.view_log("x2w-d3d12 heartbeat: 60 frames presented in 2.0 s (30.0 fps overall)\n") + self.assertIn("60 frames presented, 30.0 fps", output) + self.assertNotIn("every draw dropped", output) + self.assertNotIn("game runs offline", output) + + def test_storage_and_render_totals_are_preserved(self): + storage = ("x2w-dstorage heartbeat 10 s: requests done=12 inflated=7 failed=2 bcpack-blank=1; " + "page tokens 0 at enqueue=3, still 0 at run=1; commit peak=900 MiB current=800 MiB, " + "live physical-page sections=42") + render = ("x2w-render totals: resets 2 (failed 0), closes 2, clears 1, executes 2, " + "draws 4 (skipped 1), translated draws 3 (not drawn 2), pipelines translated 4 / missing 1, " + "null bindings 5 (entry 1, buffer 1, token 1, wrapper 1, dimension 1), " + "textures uploaded 2 (16 KiB, unreadable 1)") + output = self.view_log(storage + "\n" + render + "\n") + self.assertIn(storage, output) + self.assertIn(render, output) + self.assertIn("7 chunks decompressed", output) - self.assertIn("60 frames presented, 30.0 fps", output.getvalue()) - self.assertNotIn("every draw dropped", output.getvalue()) + def test_unknown_and_split_heartbeat(self): + first = "x2w-dstorage heartbeat 20 s: requests done=0 inflated=0 failed=0 bcpack-blank=0; " + second = "page tokens 0 at enqueue=0, still 0 at run=0; commit unknown, live physical-page sections=unknown\n" + output = self.view_log(first, second) + self.assertEqual(output.count(first + second.strip()), 1) if __name__ == "__main__": diff --git a/tools/startup/live_view.py b/tools/startup/live_view.py index 231780fef..026ef2758 100644 --- a/tools/startup/live_view.py +++ b/tools/startup/live_view.py @@ -88,6 +88,13 @@ def on_shim(line): say("storage", f"read batch complete: {m.group(1)} compressed chunks decompressed so far, {m.group(2)} failed") elif "EnqueueRequest" in line or "options=" in line or "Queue::Submit" in line or "IsComplete" in line: return + elif line.startswith("x2w-dstorage heartbeat "): + m = re.search(r"\binflated=(\d+)", line) + if m: + counts["chunks"] = int(m.group(1)) + say("storage", line) + elif line.startswith("x2w-render totals:"): + say("render", line) elif "heartbeat" in line: m = re.search(r"heartbeat: (\d+) frames presented in ([\d.]+) s \(([\d.]+) fps", line) if m: @@ -119,7 +126,7 @@ def on_shim(line): positions = {name: 0 for name in sources} partial = {name: "" for name in sources} print("Xbox2Windows local startup experiment: live log of " + os.path.abspath(rundir)) -print("Columns: time since this window opened, category, detail. The game runs offline (network opens are refused).") +print("Columns: time since this window opened, category, detail. Network refusals are shown when observed.") print("-" * 110, flush=True) finished = os.path.join(rundir, "finished.txt") ended = False From 9e056e3c4325450c2b7c35a82ea89bf6bf9125cd Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:18:09 +0100 Subject: [PATCH 094/775] tests: check previous keyboard sequence against the keyboard kind --- tests/startup_gameinput_keys.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/startup_gameinput_keys.cpp b/tests/startup_gameinput_keys.cpp index 6c065177b..84ac1f741 100644 --- a/tests/startup_gameinput_keys.cpp +++ b/tests/startup_gameinput_keys.cpp @@ -364,6 +364,7 @@ int main(int argc, char** argv) } SetEnvironmentVariableA("X2W_INPUT_KEYS", "52"); input->GetCurrentReading(kind_keyboard, kbd_device, &tmp); + const std::uint64_t key52 = tmp ? tmp->GetSequenceNumber(kind_keyboard) : 0; if (tmp) tmp->Release(); tmp = nullptr; failures += check(input->GetNextReading(pad_a, kind_gamepad, pad_device, &tmp) == reading_not_found && tmp == nullptr, @@ -384,8 +385,7 @@ int main(int argc, char** argv) IGameInputReading* kback = nullptr; failures += check(input->GetPreviousReading(pad_b, kind_keyboard, kbd_device, &kback) == S_OK && kback, "previous keyboard reading"); if (kback) { - failures += check(kback->GetSequenceNumber(kind_keyboard) < pad_b->GetSequenceNumber(kind_keyboard) && - kback->GetSequenceNumber(kind_keyboard) > key51, "previous keyboard reading skips pad-only entries"); + failures += check(kback->GetSequenceNumber(kind_keyboard) == key52 - 1 && key52 > key51, "previous keyboard reading skips pad-only entries"); kback->Release(); } pad_b->Release(); From 7ed364a1a57405a7d24f1c57286014b5d200c345 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:21:23 +0100 Subject: [PATCH 095/775] Split acceleration-structure SRVs out of slot 70; require structured stride multiple of 4 --- docs/experiments.md | 12 ++++---- docs/startup-runtime.md | 18 +++++++----- src/startup_stubs/d3d12_memory_srv.inl | 25 ---------------- src/startup_stubs/memory_srv_buffer.h | 36 ++++------------------- tests/startup_memory_srv_buffer_check.cpp | 30 ++----------------- 5 files changed, 23 insertions(+), 98 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index b3d35701c..b881b6589 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9609,17 +9609,15 @@ array size, mips, layout, flags, alignment and sample count and quality; view di component mapping, with the mip, plane and array fields for 2D and 2D-array views and the first element, count, stride and flags for buffer views (any other dimension prints its six raw words); the destination handle and whether it is a descriptor of a known CBV/SRV/UAV heap; the address and -whether its first byte is readable. Textures (2D) and buffers are supported, plus raytracing acceleration-structure views on adapters that -report raytracing support (see "Buffer and raytracing acceleration-structure memory SRVs" in -`docs/startup-runtime.md`). A buffer view must name a live placed or committed buffer, with a raw, -structured (stride up to 2048) or typed format; typed element sizes come from the format, and formats +whether its first byte is readable. Textures (2D) and buffers are supported (see "Buffer memory SRVs" in +`docs/startup-runtime.md`); acceleration-structure views are refused. A buffer view must name a live placed or committed buffer, with a raw, +structured (stride a multiple of 4, up to 2048) or typed format; typed element sizes come from the format, and formats that cannot back a typed buffer SRV (sRGB, block-compressed, depth/stencil, typeless, BGRA) are refused -with `unsupported_description`. An acceleration-structure view on an adapter without raytracing is -refused with `raytracing_unsupported`. Translated draws bind typed buffer views with the format's +with `unsupported_description`. Translated draws bind typed buffer views with the format's element size and stride. `startup_memory_srv_report` compares the line field by field for buffer, acceleration-structure -and array views and for unreadable arguments. `startup_address_srv_hardware` and +(refused) and array views and for unreadable arguments. `startup_address_srv_hardware` and `startup_address_srv_warp` also match the five lines of their refused calls (zero address, other width, interior address, a buffer view, a destination off the heap) and show the descriptor unchanged. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 87cf1b7d2..ba7da013f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -701,23 +701,21 @@ is not affected: section-backed pages already took the committed, not-aliased pa (slot 133) inside one view and across three kinds of boundary: two mapping calls, two backing sections, and single-page views. -## Buffer and raytracing acceleration-structure memory SRVs (device slot 70) +## Buffer memory SRVs (device slot 70) Device slot 70 (`src/startup_stubs/d3d12_memory_srv.inl`, validation in `src/startup_stubs/memory_srv_buffer.h`) also accepts `D3D12_RESOURCE_DIMENSION_BUFFER` descriptions with: -- `D3D12_SRV_DIMENSION_BUFFER` (raw `R32_TYPELESS`, structured `Format == UNKNOWN` with stride up to +- `D3D12_SRV_DIMENSION_BUFFER` (raw `R32_TYPELESS`, structured `Format == UNKNOWN` with a stride that is a multiple of 4 up to 2048, or typed buffers). It resolves an existing live placed (slot 133) or committed (slot 127) buffer covering `[address, address + (FirstElement + NumElements) * element_bytes)`, checks alignment and bounds, adjusts `FirstElement` by `(address - base) / element_bytes`, and forwards to `CreateShaderResourceView` (slot 18). -- `D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE` (`Format == UNKNOWN`). When the adapter - reports raytracing support (`D3D12_FEATURE_D3D12_OPTIONS5::RaytracingTier != NOT_SUPPORTED`), it - resolves the buffer at `address`, verifies 256-byte alignment on both the title address and the - resolved desktop GPU virtual address, sets `RaytracingAccelerationStructure.Location`, and - forwards to slot 18 with `pResource == nullptr`. Adapters without raytracing support refuse the - call cleanly (`raytracing_unsupported`) without removing the device. + +Acceleration-structure views (`D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE`) are not +supported and are refused. A view needs an actual built structure with the placed AS role and +lifecycle checks, which has no device test yet. Typed element bytes come from the format (1 to 16 bytes). Formats that cannot back a typed buffer SRV (sRGB, BGRA, block-compressed, depth/stencil, typeless, planar) are refused with @@ -727,5 +725,9 @@ views with the format's element size and stride. The refusal reasons are listed Checks: +`startup_memory_srv_buffer` is device-free and owns every rejection (bounds, alignment, format, +stride). `startup_address_buffer_srv_*` exercises only the resolve path with valid addresses on a +device, so it does not cover the rejections. + - `ctest --preset release --no-tests=error -R '^startup_memory_srv_(report|buffer)$' -V` - `ctest --preset release --no-tests=error -R '^startup_address_(srv|buffer_srv)_' -V` diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 4d3287238..a0c7eca7e 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -214,31 +214,6 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou return; } if (resource->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - if (static_cast(input->view.ViewDimension) == x2w_startup::srv_dimension_rt_acceleration_structure) { - D3D12_FEATURE_DATA_D3D12_OPTIONS5 opts5{}; - if (FAILED(device_of(self)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &opts5, sizeof(opts5))) || - opts5.RaytracingTier == D3D12_RAYTRACING_TIER_NOT_SUPPORTED) { - if (first_calls(refused, 8)) - log_refused_memory_srv("raytracing acceleration structure views are not supported on this adapter", - "raytracing_unsupported", resource, input, destination); - return; - } - Wrapper* buffer = existing_memory_buffer(self, input->address, resource->Width); - const ResourceInfo* info = buffer ? resource_info(buffer) : nullptr; - auto* desktop_res = buffer ? static_cast(buffer->own().real) : nullptr; - D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; - if (!buffer || !info || !desktop_res || - !x2w_startup::resolve_rt_as_srv_desc(reinterpret_cast(buffer->own().title_memory), - info->console.Width, desktop_res->GetGPUVirtualAddress(), - input->address, resource->Width, input->view, adjusted)) { - if (first_calls(refused, 8)) - log_refused_memory_srv("unavailable buffer at the supplied address", "buffer_unavailable", - resource, input, destination); - return; - } - view_slot<18, 2>(self, 0, reinterpret_cast(&adjusted), destination, 0); - return; - } const u64 elem_bytes = x2w_startup::buffer_srv_element_bytes(input->view); const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); diff --git a/src/startup_stubs/memory_srv_buffer.h b/src/startup_stubs/memory_srv_buffer.h index 688bb0c71..331edcf8e 100644 --- a/src/startup_stubs/memory_srv_buffer.h +++ b/src/startup_stubs/memory_srv_buffer.h @@ -1,5 +1,5 @@ -// Pure validation and offset/GPU-address resolution for buffer and raytracing -// acceleration-structure memory SRVs (device slot 70). +// Pure validation and offset resolution for buffer memory SRVs (device slot 70). +// Acceleration-structure views are not handled here. #pragma once #include @@ -8,8 +8,6 @@ namespace x2w_startup { -constexpr std::uint32_t srv_dimension_rt_acceleration_structure = 11; - // Byte size of a single element for typed buffer SRVs; 0 when unknown or invalid for typed buffers. inline std::uint32_t typed_buffer_format_bytes(DXGI_FORMAT format) { @@ -90,7 +88,9 @@ inline std::uint32_t buffer_srv_element_bytes(const D3D12_SHADER_RESOURCE_VIEW_D return 4; } if (v.Buffer.StructureByteStride != 0) { - if (v.Format != DXGI_FORMAT_UNKNOWN || v.Buffer.StructureByteStride > 2048) return 0; + if (v.Format != DXGI_FORMAT_UNKNOWN || v.Buffer.StructureByteStride > 2048 || + v.Buffer.StructureByteStride % 4 != 0) + return 0; return v.Buffer.StructureByteStride; } return typed_buffer_format_bytes(v.Format); @@ -99,10 +99,6 @@ inline std::uint32_t buffer_srv_element_bytes(const D3D12_SHADER_RESOURCE_VIEW_D inline bool supports_buffer_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) { if (!valid_buffer_resource_desc(r)) return false; - if (static_cast(v.ViewDimension) == srv_dimension_rt_acceleration_structure) { - return v.Format == DXGI_FORMAT_UNKNOWN && - v.Shader4ComponentMapping == D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - } const std::uint32_t elem_bytes = buffer_srv_element_bytes(v); if (!elem_bytes) return false; const std::uint64_t total_elements = r.Width / elem_bytes; @@ -131,26 +127,4 @@ inline bool resolve_buffer_srv_desc(std::uint64_t buffer_title_base, std::uint64 return true; } -inline bool resolve_rt_as_srv_desc(std::uint64_t buffer_title_base, std::uint64_t buffer_width, - D3D12_GPU_VIRTUAL_ADDRESS buffer_gpu_base, std::uint64_t address, - std::uint64_t view_width, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, - D3D12_SHADER_RESOURCE_VIEW_DESC& resolved) -{ - constexpr std::uint64_t alignment = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT; - if (static_cast(view.ViewDimension) != srv_dimension_rt_acceleration_structure || - view.Format != DXGI_FORMAT_UNKNOWN || - view.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) - return false; - if (!buffer_title_base || !buffer_gpu_base || address < buffer_title_base || !view_width) return false; - if (address % alignment != 0) return false; - const std::uint64_t offset = address - buffer_title_base; - if (offset >= buffer_width || view_width > buffer_width - offset) return false; - if (offset > UINT64_MAX - buffer_gpu_base) return false; - const D3D12_GPU_VIRTUAL_ADDRESS gpu_location = buffer_gpu_base + offset; - if (gpu_location % alignment != 0) return false; - resolved = view; - resolved.RaytracingAccelerationStructure.Location = gpu_location; - return true; -} - } // namespace x2w_startup diff --git a/tests/startup_memory_srv_buffer_check.cpp b/tests/startup_memory_srv_buffer_check.cpp index 116f08ef3..554df5afe 100644 --- a/tests/startup_memory_srv_buffer_check.cpp +++ b/tests/startup_memory_srv_buffer_check.cpp @@ -64,15 +64,6 @@ D3D12_SHADER_RESOURCE_VIEW_DESC typed_view(DXGI_FORMAT format, UINT64 first_elem return v; } -D3D12_SHADER_RESOURCE_VIEW_DESC rt_as_view(DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN) -{ - D3D12_SHADER_RESOURCE_VIEW_DESC v{}; - v.Format = format; - v.ViewDimension = static_cast(x2w_startup::srv_dimension_rt_acceleration_structure); - v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - return v; -} - } // namespace int main() @@ -108,6 +99,8 @@ int main() auto str_bad_fmt = str_ok; str_bad_fmt.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; check("structured bad format", !x2w_startup::supports_buffer_memory_srv(buf, str_bad_fmt)); + check("structured stride not multiple of 4", !x2w_startup::supports_buffer_memory_srv(buf, structured_view(0, 1, 6))); + check("structured stride 4 ok", x2w_startup::supports_buffer_memory_srv(buf, structured_view(0, 1, 4))); check("structured stride too large", !x2w_startup::supports_buffer_memory_srv(buf, structured_view(0, 1, 2052))); check("structured resolve interior", x2w_startup::resolve_buffer_srv_desc(0x10000, 1024, 0x10020, str_ok, resolved) && @@ -138,24 +131,7 @@ int main() denied_buf.Flags = D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; check("denied srv flag", !x2w_startup::supports_buffer_memory_srv(denied_buf, raw_ok)); - // Raytracing acceleration structure SRV validation and GPU VA mapping. - const auto as_ok = rt_as_view(); - check("rt as valid", x2w_startup::supports_buffer_memory_srv(buf, as_ok)); - check("rt as bad format", !x2w_startup::supports_buffer_memory_srv(buf, rt_as_view(DXGI_FORMAT_R32_TYPELESS))); - check("rt as resolve base", - x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000000ull, 0x10000, 256, as_ok, resolved) && - resolved.RaytracingAccelerationStructure.Location == 0x80000000ull); - check("rt as resolve aligned interior", - x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000000ull, 0x10100, 256, as_ok, resolved) && - resolved.RaytracingAccelerationStructure.Location == 0x80000100ull); - check("rt as unaligned address", - !x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000000ull, 0x10080, 256, as_ok, resolved)); - check("rt as unaligned gpu base", - !x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000080ull, 0x10000, 256, as_ok, resolved)); - check("rt as oob", - !x2w_startup::resolve_rt_as_srv_desc(0x10000, 1024, 0x80000000ull, 0x10300, 512, as_ok, resolved)); - if (failures) return 1; - std::printf("slot 70 buffer and rt-as memory SRV validation: all checks passed\n"); + std::printf("slot 70 buffer memory SRV validation: all checks passed\n"); return 0; } From 71ec5842ed23644e8ddabdd88ca7175645a66e20 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:22:08 +0100 Subject: [PATCH 096/775] triage_run: allowlist-only structured summary; never echo free-form log text --- docs/startup-runtime.md | 9 +- tests/startup_triage_run_check.py | 89 +++++++++++----- tools/startup/triage_run.py | 164 ++++++++++++++++++------------ 3 files changed, 168 insertions(+), 94 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0b2d65a46..e1f3a25bd 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -173,9 +173,12 @@ socket, NetBIOS and DNS devices are refused (`--offline 0` turns this off; do no adds memory dumps to the stop report. `tools/startup/triage_run.py` summarizes a log directory (and optional `--shader-cache `) -into a path-redacted, address-redacted Markdown report (`Device::slot70` refusals, unhandled -`x2w-d3d12` / trap slots, `x2w-dstorage` failures and status HRESULTs, `x2w-runtime` failing calls, -and `.fail` shader reasons). Check with `python3 -B tests/startup_triage_run_check.py` (ctest +into an allowlist-only Markdown report: known reason and outcome tokens, decimal IDs and counts, +hex HRESULT/format/flag codes, slot numbers and known shader-failure categories (`Device::slot70` +refusals, unhandled `x2w-d3d12` / trap slots, `x2w-d3d12-debug` severity/ID counts, `x2w-dstorage` +failures and status HRESULTs, `x2w-runtime` failing slots, and `.fail` shader categories). Any other +text is grouped as `other (text omitted)` and never copied; raw snippets stay in the local logs. +Check with `python3 -B tests/startup_triage_run_check.py` (ctest `startup_triage_run`). ## Launcher check diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 84ded3af9..08eadd753 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -63,14 +63,16 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: "| 2 | unsupported_description | 1 | 0 | 11 | 0 | 0x1 | 0x0 |", "| 1 | destination_outside_view_heaps | 3 | 98 | 5 | 98 | 0x105 | 0x300000 |", "| 1 | unreadable_resource | unreadable | unreadable | unreadable | unreadable | unreadable | unreadable |", - "| 1 | `x2w-noop d3d12_xs!Device::slot44` |", + "| 1 | `x2w-noop Device::slot44` |", "| 1 | `Device::slot10(CreateGraphicsPipelineState)` |", "| 2 | zlib failed |", + "| 1 | 2 | 999 |", "| 1 | OpenFile: fail (err 2) |", "| 1 | `0x80004005` |", - "| 2 | `12345678::slot5` | `0x80004005` |", + "| 2 | `slot5` | `0x80004005` |", "| 1 | `persistent_local_storage` | `0x80070005` |", "| 2 | `image_load_mip tfe` |", + f"| 1 | `{triage_run.OTHER}` |", ] for snippet in expected_snippets: if snippet not in report: @@ -94,32 +96,67 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: failures.append(f"negative control failed: leaked {secret!r} in report") -def check_redaction_helper(failures: list[str]) -> None: - cases = [ - (r'C:\Users\alice\secret\game.exe', ""), - (r'"C:\Program Files\My App\title.exe"', '""'), - ("/home/alice/dumps/run1/stderr.txt", ""), - ("/Users/alice/Desktop/tool.exe", ""), - ("ret=sample_app.exe+0x1234", "ret=+0x1234"), - ("ptr=0x00007ff712345678 hr=0x80004005", "ptr=0x hr=0x80004005"), - ] - for raw, want in cases: - got = triage_run.redact(raw) - if got != want: - failures.append(f"redact({raw!r}) = {got!r}, expected {want!r}") +PRIVATE_LINES = """\ +x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=ACMEPrivateReason res{dim=PrivateDim fmt=acme_fmt layout=0xZZ flags=acmeflag} view{dim=x fmt=y} dest=0x1 +x2w-trap acmegame_private!Device::slot31 rcx=0x1 ret=acmegame+0x10 +x2w-noop ACMEOpaqueObject rcx=0x1 +x2w-d3d12-debug [AcmeContext 7] sev=2 id=1234 loading AcmeTitle shader [secret](https://acme.example/leak) 0000018012345678 acme_widget_7f3a +x2w-d3d12 Device::slot44 view skipped: acme_widget_7f3a in AcmeModule.dll +x2w-d3d12 DEVICE REMOVED, reason 0x887a0005, first noticed after acme_widget_7f3a +x2w-dstorage options=0x1 dest=0x1 dest_size=0x1 source=0x1 offset=0x0 size=0x1 -> acme_widget_7f3a exploded +x2w-dstorage entry type 3 failed: AcmeTitle bad [secret](https://acme.example/leak) +x2w-dstorage Factory::OpenFile path="x" riid={1} -> fail acme_widget_7f3a +x2w-runtime 0000018012345678::slot9(0x1) -> 0x80004005 from +0x1 +""" +PRIVATE_SHADER_FAILS = [ + "AcmeModule: 0000018012345678 acme_widget_7f3a [secret](https://acme.example/leak)", + "v_acme_widget_7f3a_private with AcmeTitle", + "acmegame_private", + "undecodable word at +0x10: AcmeTitle shader text", + "image_load_mip tfe AcmeTitle", + "image_load_mip tfe", +] +PRIVATE_NEEDLES = [ + "Acme", "acme", "ACME", "Private", "secret", "leak", "widget", "7f3a", "exploded", + "0000018012345678", "12345678", "[", "](", "http", ".dll", "Opaque", +] + + +def check_private_text_never_echoed(failures: list[str]) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + (logdir / "stderr.txt").write_text(PRIVATE_LINES, encoding="utf-8") + cache_dir = root / "cache" + cache_dir.mkdir() + for index, text in enumerate(PRIVATE_SHADER_FAILS): + (cache_dir / f"{index:016x}.fail").write_text(text + "\n", encoding="utf-8") + report = triage_run.triage_run(logdir, shader_cache=cache_dir) + for needle in PRIVATE_NEEDLES: + if needle in report: + failures.append(f"free-form text leaked into report: {needle!r}\n{report}") + for want in [ + "| 1 | 2 | 1234 |", + "`DEVICE REMOVED 0x887a0005`", + "`x2w-trap Device::slot31`", + "`x2w-noop other (text omitted)`", + "`Device::slot44 view skipped`", + "| 1 | OpenFile: fail (other) |", + "| 1 | entry failed |", + "`slot9` | `0x80004005`", + "`undecodable word`", + "`image_load_mip tfe`", + "`v_* with modifier`", + "`other (text omitted)`", + ]: + if want not in report: + failures.append(f"missing grouped allowlist row: {want!r}") + if "| 1 | other (text omitted) | ? | ? | ? | ? | ? | ? |" not in report: + failures.append("unknown slot70 reason/values were not grouped as other/?") def check_review_regressions(failures: list[str]) -> None: - # Paths with spaces are redacted whole, in a shader .fail line and in plain text. - for raw, want in [ - (r"fxc ps: C:\Users\Alice Smith\PrivateTitle\shader.hlsl(1,1): error X3000", - "fxc ps: error X3000"), - (r"open C:\Program Files\My App\shader.hlsl failed", "open failed"), - ("read /home/Alice Smith/cache/x.bin: denied", "read denied"), - ]: - got = triage_run.redact(raw) - if got != want or "Smith" in got or "Program" in got: - failures.append(f"redact({raw!r}) = {got!r}, expected {want!r}") with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) logdir = root / "run" @@ -187,7 +224,7 @@ def check_cli_invocation(failures: list[str]) -> None: def main() -> int: failures: list[str] = [] check_aggregation_and_redaction(failures) - check_redaction_helper(failures) + check_private_text_never_echoed(failures) check_review_regressions(failures) check_empty_and_missing_dirs(failures) check_cli_invocation(failures) diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 4d38561e7..da52649df 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -1,9 +1,13 @@ #!/usr/bin/env python3 -"""Summarize a startup log directory (and optional shader cache) into redacted Markdown. - -Reads raw logs produced by tools/startup/run.ps1 / debug_launch.py and emits a -title-neutral, path-redacted, address-redacted Markdown summary suitable for a -GitHub issue. Uses only the Python 3 standard library. +"""Summarize a startup log directory (and optional shader cache) into Markdown. + +Reads raw logs produced by tools/startup/run.ps1 / debug_launch.py. The report is +built only from allowlisted structured values: known reason/outcome tokens, decimal +IDs and counts, hexadecimal HRESULT/format/flag codes, slot numbers and known +gfx2hlsl mnemonic categories. Any other text (free-form debug messages, shader +failure lines, module/object names, paths, addresses, links) is never copied; it is +grouped under a fixed "other" label. Raw snippets stay in the local log files. +Uses only the Python 3 standard library. """ from __future__ import annotations @@ -29,22 +33,60 @@ "inflated + bcpack decoded", } -# Redaction patterns (applied in order from most specific/broadest path to tokens). -RE_QUOTED_WIN_PATH = re.compile(r'"([A-Za-z]:\\[^"\r\n]+|[A-Za-z]:/[^"\r\n]+|\\\\[^\\"\r\n]+\\[^"\r\n]+)"') -# Unquoted paths: directory components may contain single spaces ("Alice Smith"), the final component may not. -_DIR_COMPONENT = r'(?:[^\\/:"\'<>|\r\n=,()]{1,64}[\\/]+)*' -_LAST_COMPONENT = r'[^\s"\'<>|]*' -RE_WIN_PATH = re.compile( - r'(?:[A-Za-z]:[\\/]+|\\\\[^\\\s"\'<>|]+\\+)' + _DIR_COMPONENT + _LAST_COMPONENT -) -RE_QUOTED_POSIX_PATH = re.compile( - r'"(/(?:home|Users|mnt|tmp|var|opt|root|srv|private|Volumes)/[^"\r\n]+)"' -) -RE_POSIX_PATH = re.compile( - r'/(?:home|Users|mnt|tmp|var|opt|root|srv|private|Volumes)/' + _DIR_COMPONENT + r'[^\s"\'<>|]+' -) -RE_EXE_NAME = re.compile(r'\b[A-Za-z0-9_.\-]+\.exe\b', re.IGNORECASE) -RE_ADDR64 = re.compile(r'\b0x[0-9a-fA-F]{9,}\b') +# Allowlists: the only values that may be copied from a log into the report. +SLOT70_REASONS = {"unsupported_description", "destination_outside_view_heaps", "unreadable_resource"} +DSTORAGE_FAIL_OUTCOMES = { + "bcpack failed", + "destination capacity exceeded", + "insufficient page grants", + "missing page grant token", + "missing page tokens", + "page destination write failed", + "read failed", + "zlib failed", +} +TRAP_TAGS = {"x2w-trap", "x2w-noop", "x2w-continue", "x2w-fail"} +OTHER = "other (text omitted)" +RE_DEC = re.compile(r"\d{1,10}\Z") +RE_HEX = re.compile(r"0x[0-9a-fA-F]{1,8}\Z") +RE_SLOT = re.compile(r"(?:[A-Za-z0-9_]+!)?(?:([A-Za-z0-9_]+)::)?slot(\d{1,4})\b") +RE_OPENFILE_FAIL = re.compile(r"fail(?: \(err (\d{1,10})\))?\Z") +MNEMONIC_FAMILY = r"(v|s|ds|buffer|tbuffer|image|flat|global|scratch|exp|lds)_[a-z0-9_]{1,40}" +SHADER_REASONS: list[tuple[re.Pattern[str], str]] = [ + (re.compile(r"(image_load_mip) (tfe|a16)\Z"), r"\1 \2"), + (re.compile(r"SDWA UNUSED_SEXT\Z"), "SDWA UNUSED_SEXT"), + (re.compile(r"SDWA dst_unused\b"), "SDWA dst_unused"), + (re.compile(r"undecodable word\b"), "undecodable word"), + (re.compile(r"numeric use of s\d+ holding\b"), "numeric use of scalar register"), + (re.compile(r"operand\b"), "unsupported operand"), + (re.compile(r"modifier\b"), "unsupported modifier"), + (re.compile(r"descriptor operand\b"), "descriptor operand"), + (re.compile(r"sampler operand\b"), "sampler operand"), + (re.compile(r"mask from descriptor data\Z"), "mask from descriptor data"), + (re.compile(r"s_load\b"), "s_load form"), + # Mnemonics are free text, so only the instruction family prefix is reported. + (re.compile(MNEMONIC_FAMILY + r" SDWA\b"), r"\1_* SDWA form"), + (re.compile(MNEMONIC_FAMILY + r" with\b"), r"\1_* with modifier"), + (re.compile(MNEMONIC_FAMILY + r"\Z"), r"\1_* instruction"), +] + + +def _dec(text: str | None) -> str: + return text if text is not None and RE_DEC.match(text) else "?" + + +def _hexcode(text: str | None) -> str: + return text.lower() if text is not None and RE_HEX.match(text) else "?" + + +def classify_shader_reason(line: str) -> str: + """Map a .fail first line to a known category token; never copies unknown text.""" + for pattern, label in SHADER_REASONS: + m = pattern.match(line) + if m: + return m.expand(label) + return OTHER + # Log line patterns matching src/startup_stubs/*. RE_SLOT70 = re.compile( @@ -79,7 +121,7 @@ ) RE_RUNTIME_CALL = re.compile( - r'x2w-(?:runtime|api)\s+([0-9a-fA-F]+::slot\d+)(?:\([^)]*\))?\s+->\s+(0x[0-9a-fA-F]+)' + r'x2w-(?:runtime|api)\s+[0-9a-fA-F]+::slot(\d+)(?:\([^)]*\))?\s+->\s+(0x[0-9a-fA-F]+)' ) RE_RUNTIME_STORAGE = re.compile( r'x2w-runtime\s+persistent local storage:\s+local object instead of\s+(0x[0-9a-fA-F]+)' @@ -89,15 +131,10 @@ ) -def redact(text: str) -> str: - """Strip local paths, executable names, and 64-bit addresses from a log snippet.""" - out = RE_QUOTED_WIN_PATH.sub('""', text) - out = RE_WIN_PATH.sub("", out) - out = RE_QUOTED_POSIX_PATH.sub('""', out) - out = RE_POSIX_PATH.sub("", out) - out = RE_EXE_NAME.sub("", out) - out = RE_ADDR64.sub("0x", out) - return out +def _slot_label(m: re.Match[str] | None) -> str: + if m is None: + return OTHER + return f"{'Device' if m.group(1) == 'Device' else 'other'}::slot{m.group(2)}" def _md_cell(value: object) -> str: @@ -136,7 +173,7 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]: """Aggregate startup telemetry counters from an iterable of log lines.""" slot70_refusals: Counter[tuple[str, str, str, str, str, str, str]] = Counter() d3d12_unhandled: Counter[str] = Counter() - d3d12_debug: Counter[tuple[str, str, str, str]] = Counter() + d3d12_debug: Counter[tuple[str, str]] = Counter() dstorage_failures: Counter[str] = Counter() dstorage_hresults: Counter[str] = Counter() runtime_failures: Counter[tuple[str, str]] = Counter() @@ -150,44 +187,44 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]: m = RE_SLOT70.search(line) if m: reason, res_raw, view_raw = m.group(1), m.group(2), m.group(3) + if reason not in SLOT70_REASONS: + reason = OTHER res = _parse_kv_block(res_raw) view = _parse_kv_block(view_raw) if "_unreadable" in res: dim = fmt = layout = flags = "unreadable" else: - dim = res.get("dim", "?") - fmt = res.get("fmt", "?") - layout = res.get("layout", "?") - flags = res.get("flags", "?") + dim = _dec(res.get("dim")) + fmt = _dec(res.get("fmt")) + layout = _hexcode(res.get("layout")) + flags = _hexcode(res.get("flags")) if "_unreadable" in view: view_dim = view_fmt = "unreadable" else: - view_dim = view.get("dim", "?") - view_fmt = view.get("fmt", "?") + view_dim = _dec(view.get("dim")) + view_fmt = _dec(view.get("fmt")) slot70_refusals[(reason, dim, fmt, view_dim, view_fmt, layout, flags)] += 1 continue # 2. x2w-trap / x2w-noop / x2w-continue / x2w-fail m = RE_TRAP_TAG.match(line) if m: - tag, target = m.group(1), redact(m.group(2)) - d3d12_unhandled[f"{tag} {target}"] += 1 + tag = m.group(1) if m.group(1) in TRAP_TAGS else OTHER + sm = RE_SLOT.search(m.group(2)) + d3d12_unhandled[f"{tag} {_slot_label(sm)}"] += 1 continue # 3. x2w-d3d12-debug m = RE_D3D12_DEBUG.search(line) if m: - ctx, sev, msg_id, msg = m.group(1), m.group(2), m.group(3), redact(m.group(4)) - if len(msg) > 120: - msg = msg[:117] + "..." - d3d12_debug[(redact(ctx), sev, msg_id, msg)] += 1 + d3d12_debug[(_dec(m.group(2)), _dec(m.group(3)))] += 1 # message text is never copied continue # 4. x2w-d3d12 unhandled/trapped/skipped slots & device removed if "x2w-d3d12" in line: m = RE_D3D12_REMOVED.search(line) if m: - d3d12_unhandled[f"DEVICE REMOVED {m.group(1)} after {redact(m.group(2))}"] += 1 + d3d12_unhandled[f"DEVICE REMOVED {_hexcode(m.group(1))}"] += 1 continue m = RE_D3D12_PIPELINE_TRAP.search(line) if m: @@ -199,14 +236,14 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]: continue m = RE_D3D12_VIEW_SKIPPED.search(line) if m: - d3d12_unhandled[f"Device::slot{m.group(1)} view skipped: {redact(m.group(2))}"] += 1 + d3d12_unhandled[f"Device::slot{_dec(m.group(1))} view skipped"] += 1 continue m = RE_D3D12_FORWARDED_RESULT.search(line) if m and not _is_failed_hresult(m.group(1))[0]: continue # forward_slot()/create_slot() telemetry of a call the desktop device implemented m = RE_D3D12_SLOT_CALL.search(line) if m: - d3d12_unhandled[m.group(1)] += 1 + d3d12_unhandled[_slot_label(RE_SLOT.search(m.group(1)))] += 1 continue # 5. x2w-dstorage failures & status HRESULTs @@ -214,12 +251,14 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]: m = RE_DSTORAGE_OUTCOME.search(line) if m: outcome = m.group(1).strip() - if outcome not in DSTORAGE_OK_OUTCOMES: - dstorage_failures[redact(outcome)] += 1 + if outcome in DSTORAGE_FAIL_OUTCOMES: + dstorage_failures[outcome] += 1 + elif outcome not in DSTORAGE_OK_OUTCOMES: + dstorage_failures[OTHER] += 1 continue m = RE_DSTORAGE_ENTRY_FAIL.search(line) if m: - dstorage_failures[f"entry failed: {redact(m.group(1))}"] += 1 + dstorage_failures["entry failed"] += 1 continue m = RE_DSTORAGE_ZLIB_FAIL.search(line) if m: @@ -227,7 +266,8 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]: continue m = RE_DSTORAGE_OPENFILE_FAIL.search(line) if m: - dstorage_failures[f"OpenFile: {redact(m.group(1))}"] += 1 + fm = RE_OPENFILE_FAIL.match(m.group(1).strip()) + dstorage_failures["OpenFile: fail" + (f" (err {fm.group(1)})" if fm and fm.group(1) else "" if fm else " (other)")] += 1 continue m = RE_DSTORAGE_HRESULT.search(line) if m: @@ -247,7 +287,7 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]: if m: failed, norm_hr = _is_failed_hresult(m.group(2)) if failed: - runtime_failures[(m.group(1), norm_hr)] += 1 + runtime_failures[(f"slot{m.group(1)}", norm_hr)] += 1 continue m = RE_RUNTIME_STORAGE.search(line) if m: @@ -256,7 +296,7 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]: continue m = RE_RUNTIME_GAMESAVE.search(line) if m: - runtime_failures[("game_save_update", f"status {m.group(1)}")] += 1 + runtime_failures[("game_save_update", f"status {_dec(m.group(1).lstrip('-')) if m.group(1).lstrip('-').isdigit() else '?'}")] += 1 continue return { @@ -287,10 +327,7 @@ def summarize_shader_cache(cache_dir: Path | None) -> Counter[str]: break if not first_line: first_line = "(empty .fail)" - cleaned = redact(first_line) - if len(cleaned) > 120: - cleaned = cleaned[:117] + "..." - reasons[cleaned] += 1 + reasons["(empty .fail)" if first_line == "(empty .fail)" else classify_shader_reason(first_line)] += 1 return reasons @@ -324,7 +361,7 @@ def format_markdown( shader_cache_provided: bool, max_items: int, ) -> str: - """Render aggregated counters as clean-room Markdown.""" + """Render aggregated counters as allowlisted Markdown.""" out: list[str] = [ "## Startup Run Triage Summary", "", @@ -382,13 +419,10 @@ def format_markdown( dbg = summary["d3d12_debug"] if dbg: out.extend(["### `x2w-d3d12-debug` Messages", ""]) - dbg_rows = [ - [count, ctx, sev, msg_id, msg] - for (ctx, sev, msg_id, msg), count in dbg.most_common() - ] + dbg_rows = [[count, sev, msg_id] for (sev, msg_id), count in dbg.most_common()] out.extend( _format_table( - ["Count", "Context", "Sev", "ID", "Message (redacted)"], + ["Count", "Sev", "ID"], dbg_rows, len(dbg), sum(dbg.values()), @@ -458,7 +492,7 @@ def triage_run( shader_cache: Path | None = None, max_items: int = 16, ) -> str: - """Scan logdir (and optional shader_cache) and return a redacted Markdown summary.""" + """Scan logdir (and optional shader_cache) and return an allowlisted Markdown summary.""" log_files = iter_log_files(logdir) # run.ps1 / debug_launch.py capture stderr.txt while X2W_TRAP_LOG appends the same lines to trap.log: @@ -500,7 +534,7 @@ def _line_stream() -> Iterable[str]: def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( - description="Summarize startup logs and optional shader cache into redacted Markdown." + description="Summarize startup logs and optional shader cache into allowlisted Markdown." ) parser.add_argument("logdir", type=Path, help="Startup log directory or single log file") parser.add_argument( From be3ebcf678a81705445f245d3ec6a50122c18801 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:23:54 +0800 Subject: [PATCH 097/775] docs: record the indexed mesh draw on Intel Xe2 The single-group mesh entry section gives the command for mesh_indexed_draw_* but no adapter result. Record the Intel Arc 140T run at 06e2ff78: all 1,024 pixels matched in each of the four draws the fixture runs, with zero D3D12 debug errors and warnings. Docs only. --- docs/experiments.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 805665c15..f0bea5d1b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2634,6 +2634,8 @@ python3 -B tests/mesh_indexed_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM ctest --preset dev --no-tests=error -R "^mesh_indexed_draw_" -V ``` +The fixture runs four draws. On Windows 11 build 26300.9974, the Intel Arc 140T (32.0.101.8132) matched all 1,024 pixels in each of them, with zero D3D12 debug errors and warnings. + The source-built `mesh_cbv_order` test binds two separate upload resources as root CBVs and exchanges their GPU addresses for the second draw. The mesh entry adds the float at byte 4 of b0 to the float at byte 12 of b1. The translated From 8b2df3dc5edfbc34498cde57b80de9d35413ad52 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 20:23:58 +0800 Subject: [PATCH 098/775] test: bound the gfx1030 upper raw LOD comparison --- docs/experiments.md | 11 ++++++++--- tests/desktop_gpu.h | 3 ++- tests/offscreen_check.cpp | 7 +++++++ tests/pixel_aot_render.cpp | 13 ++++++++++++- tests/pixel_get_lod_check.py | 31 +++++++++++++++++++++++-------- 5 files changed, 52 insertions(+), 13 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 8c9c0d222..4d9b90ebf 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -698,9 +698,14 @@ For each draw, the GPU fixture compiles the translated program and an with the same texture, sampler, viewport and constants. It compares all 256 FP32 channels and prints the first pixel's RGBA words and a SHA-256 of the full readback for each path. The upper-clamp readback is in the -order `(raw LOD - 2, clamped LOD, 0, 1)`. Both paths also undergo the -strict CPU-reference check. For driver comparisons, the `release` preset -runs the same fixtures. +order `(raw LOD - 2, clamped LOD, 0, 1)`. Both paths also undergo the CPU +reference check. The only non-bitwise allowance is one LOD step (`1/256`, +from `D3D12_MIP_LOD_FRACTIONAL_BIT_COUNT`) in the rendered upper-clamp red +channel: the RTX 4060 Laptop read `-0.00390625` on both paths instead of zero. +All other channels, the clear region and the signed negative LOD remain +exact, as does the comparison between the two GPU paths. The fixture also +injects a one-step and a two-step deviation to check that only the former +is accepted. For driver comparisons, the `release` preset runs the same fixtures. ```powershell cmake --build --preset dev --target offscreen_check diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 4fdb64dbc..cf119d227 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -63,7 +63,8 @@ void check_translated_pixel(ID3D12Device* device, const char* path, bool swapRB, void check_attribute_pixel(ID3D12Device* device, const char* shader, const char* reference, bool rg); void check_compute_to_pixel(ID3D12Device* device, const char* compute, const char* pixel, const char* reference, const char* previous); -void check_pixel_quad_lod(ID3D12Device* device, const char* shader, const char* rawReadback = nullptr); +void check_pixel_quad_lod(ID3D12Device* device, const char* shader, const char* rawReadback = nullptr, + bool allowUpperRawLodStep = false); void check_pixel_mip_clamp(ID3D12Device* device, const char* shader, unsigned expectedLevel); void check_pixel_mip_blend(ID3D12Device* device, const char* shader, float clamp, float tolerance); void check_pixel_compare(ID3D12Device* device, const char* shader, const char* reference); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index cac5ab66c..2e043b111 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -749,6 +749,12 @@ OperationResult run_check_pixel_quad_lod(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +OperationResult run_check_pixel_get_lod_upper(const OperationContext& ctx) +{ + check_pixel_quad_lod(ctx.device, ctx.argv[3], ctx.argv[4], true); + return {OutcomeKind::pass, nullptr}; +} + OperationResult run_check_pixel_mip_clamp(const OperationContext& ctx) { const std::string_view level = ctx.argv[4]; @@ -1261,6 +1267,7 @@ const OperationSpec kOperations[] = { {"--check-pixel-attribute", 5, 5, nullptr, kNoGate, run_check_pixel_attribute}, {"--check-pixel-attribute-rg", 5, 5, nullptr, kNoGate, run_check_pixel_attribute_rg}, {"--check-pixel-quad-lod", 4, 5, nullptr, kNoGate, run_check_pixel_quad_lod}, + {"--check-pixel-get-lod-upper", 5, 5, nullptr, kNoGate, run_check_pixel_get_lod_upper}, {"--spirv-minlod-quad-lod", 4, 4, nullptr, kGateSm60MinLodSmoke, run_check_pixel_quad_lod}, // Keep the fractional point-filter fixture on its existing gate (#809). {"--check-pixel-mip-clamp", 5, 5, nullptr, kGateSm66MinLod, run_check_pixel_mip_clamp}, diff --git a/tests/pixel_aot_render.cpp b/tests/pixel_aot_render.cpp index 39d3aa034..861315d49 100644 --- a/tests/pixel_aot_render.cpp +++ b/tests/pixel_aot_render.cpp @@ -146,6 +146,7 @@ struct MipDraw { UINT requestedMip = 0; bool isTailDraw = false; bool partialQuad = false; + bool allowUpperRawLodStep = false; }; struct Extent { @@ -474,6 +475,14 @@ void draw_verified(ID3D12Device* device, const char* path, const std::vector Date: Tue, 24 Nov 2026 13:26:02 +0100 Subject: [PATCH 099/775] tests: slot 70 refuses an acceleration-structure view and keeps the previous descriptor --- tests/startup_address_buffer_srv_check.py | 8 ++++++- tests/startup_address_srv.cpp | 29 ++++++----------------- 2 files changed, 14 insertions(+), 23 deletions(-) diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index 52745d4b9..97444f5e1 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -17,6 +17,12 @@ def check_refusal_lines(log): + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " + r"view\{dim=1 fmt=39 map=0x1688 first=0 count=4 stride=0 flags=0x1 \(buffer views are not supported\)\} " + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + prefix + + r"unsupported memory SRV arguments: reason=unsupported_description " + + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " + + r"view\{dim=11 fmt=0 map=0x1688 raw=(00000000,){5}00000000 " + + r"\(acceleration structure views are not supported\)\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", ] lines = [line.rstrip() for line in log.splitlines() if "Device::slot70" in line] if len(lines) != len(expected): @@ -50,7 +56,7 @@ def check(directory, consumer, backend): if actual != expected: raise AssertionError(f"actual {actual.hex()} expected {expected.hex()}") check_refusal_lines(trap_log.read_text(errors="replace")) - print(f"{backend}: buffer memory SRV (raw base, raw interior, structured, refused unaligned) exact") + print(f"{backend}: buffer memory SRV (raw base, raw interior, structured, refused unaligned, refused acceleration structure) exact") return 0 diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 588c44b40..20c0bd605 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -313,30 +313,15 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) structured.view.Buffer.StructureByteStride = 4; structured.address = ptr(buf0); invoke(guest, 70, ptr(&desc), ptr(&structured), cpu); + // An acceleration-structure view is refused; draw(4) proves the structured descriptor stayed in place. + ViewAt as_view{}; + as_view.view.Format = DXGI_FORMAT_UNKNOWN; + as_view.view.ViewDimension = static_cast(11); + as_view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + as_view.address = ptr(buf0); + invoke(guest, 70, ptr(&desc), ptr(&as_view), cpu); draw(4); - // Exercise RT acceleration-structure memory SRV when the adapter supports raytracing. - D3D12_FEATURE_DATA_D3D12_OPTIONS5 opts5{}; - if (SUCCEEDED(desktop->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &opts5, sizeof(opts5))) && - opts5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED) { - static std::array raw_as_mem{}; - auto* const as_mem = reinterpret_cast((ptr(raw_as_mem.data()) + 0xffff) & ~Word{0xffff}); - D3D12_RESOURCE_DESC as_desc = desc; - as_desc.Width = 512; - as_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - void* as_res = nullptr; - if (FAILED(static_cast(invoke(guest, 133, ptr(as_mem), ptr(&as_desc), - D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, 0, - ptr(&__uuidof(ID3D12Resource)), ptr(&as_res))))) return 48; - ViewAt as_view{}; - as_view.view.Format = DXGI_FORMAT_UNKNOWN; - as_view.view.ViewDimension = static_cast(11); - as_view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - as_view.address = ptr(as_mem); - invoke(guest, 70, ptr(&as_desc), ptr(&as_view), cpu); - if (FAILED(desktop->GetDeviceRemovedReason())) return 49; - } - raw.address = ptr(buf0); raw.view.Buffer.FirstElement = 0; invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); From e4454d0c8254e9cad6b0be9c443ec70531774915 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:26:43 +0800 Subject: [PATCH 100/775] docs: record the compute-produced palette draw on Intel Xe2 The compute_mesh_texture paragraph records the two palettes and the 276-pixel stale-binding control. Append the Intel Arc 140T at 06e2ff78: both palettes matched over all 1,024 pixels and the stale SRV differed at the same 276 pixels, with zero debug errors and warnings. Docs only. --- docs/experiments.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index 805665c15..4ed36339e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2711,7 +2711,10 @@ copy, and draw share one direct command list. The test reads back the final Two independently generated palettes match their CPU references. In the stale-binding control, both producers run but the draw binds the first texture while expecting the second. All 276 covered pixels differ while the mesh -export trace and all 748 clear pixels match. +export trace and all 748 clear pixels match. On Windows 11 build 26300.9974, the +Intel Arc 140T (32.0.101.8132) matched both palettes over all 1,024 pixels and +reported the same 276 differing pixels for the stale SRV, with zero D3D12 debug +errors and warnings. ```powershell ctest --preset dev --no-tests=error -R '^compute_mesh_texture_(warp|hardware)$' -V From b1d434278026e3cb098d8ad574e2b90d6c9ae8f3 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 20:28:41 +0800 Subject: [PATCH 101/775] Preserve existing channel mappings and reset resampling on reopen --- src/startup_stubs/audio_sink.cpp | 1 + src/startup_stubs/audio_sink.h | 7 +------ tests/startup_audio_pure_check.h | 9 +++++++++ 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/startup_stubs/audio_sink.cpp b/src/startup_stubs/audio_sink.cpp index c8fde0258..635f10040 100644 --- a/src/startup_stubs/audio_sink.cpp +++ b/src/startup_stubs/audio_sink.cpp @@ -91,6 +91,7 @@ std::string AudioSink::open() return "endpoint services unavailable"; buffer_frames_ = frames; p_ = std::move(impl); + resample_.reset(); return {}; } diff --git a/src/startup_stubs/audio_sink.h b/src/startup_stubs/audio_sink.h index 4f71bac2a..c55ffbf76 100644 --- a/src/startup_stubs/audio_sink.h +++ b/src/startup_stubs/audio_sink.h @@ -61,14 +61,9 @@ inline bool is_valid_sample_rate(uint32_t rate) return rate >= 1000u && rate <= 384000u; } -inline bool is_supported_channel_count(uint32_t channels) -{ - return channels == 1u || channels == 2u || channels == 6u || channels == 8u; -} - inline bool is_supported_channel_conversion(uint32_t in_ch, uint32_t out_ch) { - if (!is_supported_channel_count(in_ch) || !is_supported_channel_count(out_ch)) return false; + if (in_ch == 0 || out_ch == 0) return false; if (in_ch == out_ch || in_ch == 1u) return true; if (in_ch == 2u && out_ch == 1u) return true; if ((in_ch == 6u || in_ch == 8u) && (out_ch == 1u || out_ch == 2u)) return true; diff --git a/tests/startup_audio_pure_check.h b/tests/startup_audio_pure_check.h index 17c4a1b7a..77a6a24d5 100644 --- a/tests/startup_audio_pure_check.h +++ b/tests/startup_audio_pure_check.h @@ -36,6 +36,15 @@ inline int check_pure() if (!convert_block(mono16, tone.data(), 480, {SampleKind::Pcm16, 1, 44100}, out) || out.size() != 441 * 2) return 16; if (convert_block(stereo16, out.data(), 120, {SampleKind::Pcm16, 6, 48000}, back)) return 17; // unsupported upmix + // Keep the existing equal-channel and mono copy paths on quad endpoints. + const BlockFormat quad_f{SampleKind::Float32, 4, 48000}; + const float quad[4] = {0.125f, -0.25f, 0.375f, -0.5f}; + if (!convert_block(quad_f, quad, 1, quad_f, out) || out.size() != sizeof(quad) || + std::memcmp(out.data(), quad, sizeof(quad)) != 0) return 24; + if (!convert_block(mono_f, quad, 1, quad_f, out) || out.size() != sizeof(quad)) return 25; + for (size_t channel = 0; channel < 4; ++channel) + if (read_sample(quad_f, out.data(), channel) != quad[0]) return 26; + // Stereo -> mono fold-down. { const float st_data[4] = {0.8f, -0.2f, 0.4f, 0.4f}; From 204e11a1e5471ac4dfc4b7f82cd1e6e0ebf7d220 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:29:28 +0800 Subject: [PATCH 102/775] docs: record the XCL-08 compute list on Intel Xe2 The d3d12x compute-list section records in-box WARP and an RX 9060 XT. Add the Intel Arc 140T at 06e2ff78 with the debug layer enabled: 64-byte view increments on both heaps, a non-zero GPU start for the visible heap, the same 0x0afb0285 hash as WARP across 320 words, and the omitted-dispatch control at its 192 expected mismatches with the first at word 64. Docs only. --- docs/experiments.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 805665c15..c14dd9142 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5914,6 +5914,8 @@ start for the non-visible heap. No case failed; the first limit is that the wron controls are source-owned because the debug layer was unavailable. The hardware case returns 77 when no physical adapter is available. +On Windows 11 build 26300.9974 with the debug layer enabled, the Intel Arc 140T (vendor `8086`, device `7d51`, driver `32.0.101.8132`) passed the hardware case with 64-byte view increments on both heaps and a non-zero GPU start for the visible heap. Its positive readback matched all 320 words with the same `0x0afb0285` hash as WARP, and the omitted-dispatch control reported its 192 expected mismatches with the first at word 64. + The boundary is the desktop device path, not a claimed console command-list ABI. The fixture uses the desktop allocator, command-list, barrier, clear, copy and queue methods on the XCL-08 device. It does not establish a console command-list creation export, console From 3f4455365a8f3b63c1ddc986e020b07672db481e Mon Sep 17 00:00:00 2001 From: ammar Date: Tue, 24 Nov 2026 14:31:24 +0200 Subject: [PATCH 103/775] cpu: restrict --host-cpu in cpu_switch_aot to read-only RDFSBASE, RDGSBASE, and RDPID --- CMakeLists.txt | 2 +- docs/experiments.md | 14 +- tests/cpu/switch_fsgsbase_rdpid.asm | 133 ++++++++-------- tests/cpu/switch_fsgsbase_rdpid.def | 14 +- tests/cpu/switch_fsgsbase_rdpid_check.py | 195 ++++++++++++----------- tools/cpu_switch_aot.py | 33 ++-- 6 files changed, 195 insertions(+), 196 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1bb81b917..957171fd2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2140,7 +2140,7 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$") cpu_asm_fixture(cpu_switch_fsgsbase_rdpid switch_fsgsbase_rdpid) cpu_translation(cpu_switch_fsgsbase_rdpid cpu_switch_aot - "rdfsbase_32,rdfsbase_64,rdgsbase_32,rdgsbase_64,wrfsbase_32_roundtrip,wrfsbase_64_roundtrip,wrgsbase_32_roundtrip,wrgsbase_64_roundtrip,wrfsgsbase_nonvolatile,rdpid_64,rdpid_twice,flag_preserve_fsgsbase_rdpid,unused_host_reads" + "rdfsbase_32,rdfsbase_64,rdgsbase_32,rdgsbase_64,read_host_nonvolatile,rdpid_64,rdpid_twice,flag_preserve_fsgsbase_rdpid,unused_host_reads" HOST_CPU) add_test(NAME cpu_aot_switch_fsgsbase_rdpid COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/switch_fsgsbase_rdpid_check.py" diff --git a/docs/experiments.md b/docs/experiments.md index b72dc2bc1..f9167e864 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9768,13 +9768,13 @@ The [MASM fixture](../tests/cpu/sse4a.asm) exports 24 translated `op_*` function Not covered by this experiment: non-temporal cache-bypass hints, runtime `offset + width > 64` hardware-undefined behavior in register-form `extrq`/`insertq`, control flow or nonvolatile prologues, and title CPU code execution. -## Host-CPU FSGSBASE and RDPID lifting in cpu_switch_aot +## Host-CPU RDFSBASE, RDGSBASE, and RDPID lifting in cpu_switch_aot -[The switch translator](../tools/cpu_switch_aot.py) adds an opt-in `--host-cpu` (`host_cpu=True`) mode lifting `rdfsbase`, `rdgsbase`, `wrfsbase`, `wrgsbase` (32- and 64-bit register forms), and `rdpid` (64-bit register form) from `docs/coverage/x64_zen2.tsv` group `Integer` to the `` intrinsics (`_readfsbase_u32`, `_readfsbase_u64`, `_readgsbase_u32`, `_readgsbase_u64`, `_writefsbase_u32`, `_writefsbase_u64`, `_writegsbase_u32`, `_writegsbase_u64`, `_rdpid_u32`): +[The switch translator](../tools/cpu_switch_aot.py) adds an opt-in `--host-cpu` (`host_cpu=True`) mode lifting read-only `rdfsbase`, `rdgsbase` (32- and 64-bit register forms), and `rdpid` (64-bit register form) from `docs/coverage/x64_zen2.tsv` group `Integer` to the `` intrinsics (`_readfsbase_u32`, `_readfsbase_u64`, `_readgsbase_u32`, `_readgsbase_u64`, `_rdpid_u32`): -- `rdfsbase` / `rdgsbase` / `rdpid` read into a `const volatile` temporary before assigning the destination (zero-extending 32-bit `rdfsbase`/`rdgsbase` and 64-bit `rdpid` into the full 64-bit register) so `/O2` preserves unreferenced reads and execution order. -- `wrfsbase` / `wrgsbase` record their operand as a source read (not a destination write), wrap the intrinsic in `std::atomic_signal_fence(std::memory_order_seq_cst)`, and reject undefined source registers. -- All five instructions are registered in `FLAG_NEUTRAL` so arithmetic flags are preserved across them, and all five are refused when `host_cpu` is omitted, when `rsp`/`esp` is addressed, when a `lock`/`rep`/`repne`/segment prefix is present, or when `rdpid` uses its 32-bit encoding. +- `rdfsbase`, `rdgsbase`, and `rdpid` read into a `const volatile` temporary before assigning the destination (zero-extending 32-bit `rdfsbase`/`rdgsbase` and 64-bit `rdpid` into the full 64-bit register) so `/O2` preserves unreferenced reads and execution order. +- All three instructions are registered in `FLAG_NEUTRAL` so arithmetic flags are preserved across them, and all three are refused when `host_cpu` is omitted, when `rsp`/`esp` is addressed, when a `lock`/`rep`/`repne`/segment prefix is present, or when `rdpid` uses its 32-bit encoding. +- Host segment-base writes (`wrfsbase`, `wrgsbase`) remain outside this read-only profile and are refused both with and without `--host-cpu`. ```powershell cmake --build --preset dev --target cpu_switch_fsgsbase_rdpid cpu_switch_fsgsbase_rdpid_lifted @@ -9783,6 +9783,6 @@ ctest --preset dev --no-tests=error -R '^cpu_aot_switch_fsgsbase_rdpid$' -V ### Measured results and open scope -The [MASM fixture](../tests/cpu/switch_fsgsbase_rdpid.asm) exports 13 translated functions covering 32- and 64-bit `rdfsbase`/`rdgsbase` (with high-bit prefill), canonical `wrfsbase`/`wrgsbase` round-trips that save and restore `FS_BASE` and the Windows TEB `GS_BASE`, nonvolatile `rbx`/`r12` save/restore, `rdpid` single and repeated reads, `FLAG_NEUTRAL` flag preservation across `add` to `setb`/`sete`/`sets`/`seto`/`setp`, and unused reads, plus native `CPUID.07H` and `RDTSCP` helpers and four rejected negative exports. [The differential check](../tests/cpu/switch_fsgsbase_rdpid_check.py) exits 77 if `CPUID.07H` lacks `FSGSBASE` (`EBX[0]`) or `RDPID` (`ECX[22]`) and otherwise pins the thread to up to four logical processors, verifying 376 CMake-lifted and 376 `/O2`-lifted checks across `dev` and `release` builds against native execution and `RDTSCP` `IA32_TSC_AUX` (while preserving `FS_BASE`/`GS_BASE` on every call), four `/O2` mutated-C++ negative controls (`keep_high32`, `drop_wrfsgsbase`, `constant_rdpid`, `clobber_flags`), 20 unit rejection controls, and 6 PE-patched DLL rejection controls, while recording decoded mnemonics through `FORM_COVERAGE_RECORD`. +The [MASM fixture](../tests/cpu/switch_fsgsbase_rdpid.asm) exports 9 translated functions covering 32- and 64-bit `rdfsbase`/`rdgsbase` (with high-bit prefill), nonvolatile `rbx`/`r12`/`r13` reads, `rdpid` single and repeated reads, `FLAG_NEUTRAL` flag preservation across `add` to `setb`/`sete`/`sets`/`seto`/`setp`, and unused reads, plus native-only `CPUID.07H`, `RDTSCP`, and `FS_BASE`-roundtrip helpers and 7 rejected negative exports (including 32- and 64-bit `wrfsbase`/`wrgsbase`). [The differential check](../tests/cpu/switch_fsgsbase_rdpid_check.py) exits 77 if `CPUID.07H` lacks `FSGSBASE` (`EBX[0]`) or `RDPID` (`ECX[22]`) and otherwise pins the thread to up to four logical processors, verifying 232 CMake-lifted and 232 `/O2`-lifted checks across `dev` and `release` builds against native execution (including canonical `FS_BASE` sweeps via the native-only helper and `RDTSCP` `IA32_TSC_AUX`), five `/O2` mutated-C++ negative controls (`keep_high32`, `truncate_64`, `swap_fs_gs`, `constant_rdpid`, `clobber_flags`), 27 unit/MASM rejection controls, and 9 PE-patched DLL rejection controls, while recording decoded mnemonics through `FORM_COVERAGE_RECORD`. -Not covered by this experiment: non-canonical `wrfsbase`/`wrgsbase` `#GP` fault behavior, cross-thread `FS_BASE`/`GS_BASE` migration, and title CPU code execution. +Not covered by this experiment: host segment-base writes (`wrfsbase`/`wrgsbase`, which require an explicit isolation/restoration profile), cross-thread `FS_BASE`/`GS_BASE` migration, and title CPU code execution. diff --git a/tests/cpu/switch_fsgsbase_rdpid.asm b/tests/cpu/switch_fsgsbase_rdpid.asm index 0d653c706..b89c9086f 100644 --- a/tests/cpu/switch_fsgsbase_rdpid.asm +++ b/tests/cpu/switch_fsgsbase_rdpid.asm @@ -1,7 +1,7 @@ ; coverage: record cpu_aot_switch_fsgsbase_rdpid -; Source-built MASM fixture for RDFSBASE, RDGSBASE, WRFSBASE, WRGSBASE, and RDPID -; in tools/cpu_switch_aot.py (--host-cpu opt-in), plus native CPUID/RDTSCP helpers -; and negative controls. +; Source-built MASM fixture for read-only RDFSBASE, RDGSBASE, and RDPID in +; tools/cpu_switch_aot.py (--host-cpu opt-in), plus native CPUID/RDTSCP/FS_BASE +; helpers and negative controls (including host segment-base write rejections). ; Every translated export uses the Windows x64 ABI: RCX, RDX, R8 -> RAX. .code @@ -33,66 +33,28 @@ rdgsbase_64 PROC FRAME ret rdgsbase_64 ENDP -wrfsbase_32_roundtrip PROC FRAME - .endprolog - rdfsbase r9 - wrfsbase ecx - mov rax, -1 - rdfsbase rax - wrfsbase r9 - ret -wrfsbase_32_roundtrip ENDP - -wrfsbase_64_roundtrip PROC FRAME - .endprolog - rdfsbase r9 - wrfsbase rcx - rdfsbase rax - wrfsbase r9 - ret -wrfsbase_64_roundtrip ENDP - -wrgsbase_32_roundtrip PROC FRAME - .endprolog - rdgsbase r9 - wrgsbase ecx - mov rax, -1 - rdgsbase rax - wrgsbase r9 - ret -wrgsbase_32_roundtrip ENDP - -wrgsbase_64_roundtrip PROC FRAME - .endprolog - rdgsbase r9 - wrgsbase rcx - rdgsbase rax - wrgsbase r9 - ret -wrgsbase_64_roundtrip ENDP - -wrfsgsbase_nonvolatile PROC FRAME +read_host_nonvolatile PROC FRAME push rbx .pushreg rbx push r12 .pushreg r12 + push r13 + .pushreg r13 .endprolog rdfsbase rbx rdgsbase r12 - wrfsbase rcx - rdfsbase r10 - wrfsbase rbx - wrgsbase rdx - rdgsbase r11 - wrgsbase r12 - mov QWORD PTR [r8], r10 - mov QWORD PTR [r8+8], r11 - mov rax, r10 - xor rax, r11 + rdpid r13 + mov QWORD PTR [r8], rbx + mov QWORD PTR [r8+8], r12 + mov QWORD PTR [r8+16], r13 + mov rax, rbx + xor rax, r12 + xor rax, r13 + pop r13 pop r12 pop rbx ret -wrfsgsbase_nonvolatile ENDP +read_host_nonvolatile ENDP rdpid_64 PROC FRAME .endprolog @@ -113,19 +75,18 @@ rdpid_twice ENDP flag_preserve_fsgsbase_rdpid PROC FRAME .endprolog + add rcx, rdx rdfsbase r9 rdgsbase r10 - add rcx, rdx - rdfsbase rax - rdgsbase r11 - wrfsbase r9 - wrgsbase r10 rdpid r11 setb BYTE PTR [r8] sete BYTE PTR [r8+1] sets BYTE PTR [r8+2] seto BYTE PTR [r8+3] setp BYTE PTR [r8+4] + mov QWORD PTR [r8+8], r9 + mov QWORD PTR [r8+16], r10 + mov QWORD PTR [r8+24], r11 mov rax, rcx ret flag_preserve_fsgsbase_rdpid ENDP @@ -139,7 +100,7 @@ unused_host_reads PROC FRAME ret unused_host_reads ENDP -; --- Native-only host CPUID / RDTSCP helpers (never translated) --- +; --- Native-only host helpers (never translated) --- native_host_features PROC FRAME push rbx @@ -173,21 +134,56 @@ native_rdtscp_aux PROC FRAME ret native_rdtscp_aux ENDP +; Temporarily sets FS_BASE to RCX around calling RDX(0, 0, 0) and restores FS_BASE. +; Windows x64 uses GS_BASE for the TEB; FS_BASE is unused by the CRT/OS. +native_with_fsbase PROC FRAME + push rbx + .pushreg rbx + sub rsp, 32 + .allocstack 32 + .endprolog + rdfsbase rbx + wrfsbase rcx + mov r10, rdx + xor ecx, ecx + xor edx, edx + xor r8d, r8d + call r10 + wrfsbase rbx + add rsp, 32 + pop rbx + ret +native_with_fsbase ENDP + ; --- Negative controls (refused by translator; never translated in build) --- -neg_undef_wrfsbase PROC FRAME +neg_wrfsbase_32 PROC FRAME + .endprolog + wrfsbase ecx + xor eax, eax + ret +neg_wrfsbase_32 ENDP + +neg_wrfsbase_64 PROC FRAME + .endprolog + wrfsbase rcx + xor eax, eax + ret +neg_wrfsbase_64 ENDP + +neg_wrgsbase_32 PROC FRAME .endprolog - wrfsbase r10 + wrgsbase ecx xor eax, eax ret -neg_undef_wrfsbase ENDP +neg_wrgsbase_32 ENDP -neg_undef_wrgsbase PROC FRAME +neg_wrgsbase_64 PROC FRAME .endprolog - wrgsbase r11d + wrgsbase rcx xor eax, eax ret -neg_undef_wrgsbase ENDP +neg_wrgsbase_64 ENDP neg_rsp_rdfsbase PROC FRAME .endprolog @@ -196,6 +192,13 @@ neg_rsp_rdfsbase PROC FRAME ret neg_rsp_rdfsbase ENDP +neg_rsp_rdgsbase PROC FRAME + .endprolog + rdgsbase rsp + xor eax, eax + ret +neg_rsp_rdgsbase ENDP + neg_rsp_rdpid PROC FRAME .endprolog rdpid rsp diff --git a/tests/cpu/switch_fsgsbase_rdpid.def b/tests/cpu/switch_fsgsbase_rdpid.def index 83df7e1f1..7766796d2 100644 --- a/tests/cpu/switch_fsgsbase_rdpid.def +++ b/tests/cpu/switch_fsgsbase_rdpid.def @@ -3,18 +3,18 @@ EXPORTS rdfsbase_64 rdgsbase_32 rdgsbase_64 - wrfsbase_32_roundtrip - wrfsbase_64_roundtrip - wrgsbase_32_roundtrip - wrgsbase_64_roundtrip - wrfsgsbase_nonvolatile + read_host_nonvolatile rdpid_64 rdpid_twice flag_preserve_fsgsbase_rdpid unused_host_reads native_host_features native_rdtscp_aux - neg_undef_wrfsbase - neg_undef_wrgsbase + native_with_fsbase + neg_wrfsbase_32 + neg_wrfsbase_64 + neg_wrgsbase_32 + neg_wrgsbase_64 neg_rsp_rdfsbase + neg_rsp_rdgsbase neg_rsp_rdpid diff --git a/tests/cpu/switch_fsgsbase_rdpid_check.py b/tests/cpu/switch_fsgsbase_rdpid_check.py index 6fec9cd7c..e0efa4380 100644 --- a/tests/cpu/switch_fsgsbase_rdpid_check.py +++ b/tests/cpu/switch_fsgsbase_rdpid_check.py @@ -1,5 +1,6 @@ """Differential checks, mutated-C++ controls, and unit/PE rejection controls -for RDFSBASE, RDGSBASE, WRFSBASE, WRGSBASE, and RDPID in tools/cpu_switch_aot.py. +for read-only RDFSBASE, RDGSBASE, and RDPID (and rejection of WRFSBASE/WRGSBASE) +in tools/cpu_switch_aot.py. """ import ctypes @@ -26,11 +27,7 @@ "rdfsbase_64", "rdgsbase_32", "rdgsbase_64", - "wrfsbase_32_roundtrip", - "wrfsbase_64_roundtrip", - "wrgsbase_32_roundtrip", - "wrgsbase_64_roundtrip", - "wrfsgsbase_nonvolatile", + "read_host_nonvolatile", "rdpid_64", "rdpid_twice", "flag_preserve_fsgsbase_rdpid", @@ -47,15 +44,6 @@ 0xFFFFFFFF80000001, ) -WR32_VALUES = ( - 0x0000000000000000, - 0x0000000012345678, - 0x0000000080000001, - 0x00007FFF80000001, - 0xDEAD0000BEEF1234, - 0xFFFFFFFFFFFFFFFF, -) - FLAG_PAIRS = ( (0, 0), (1, 0), @@ -90,7 +78,7 @@ def bind_lib(dll_path, prefix=""): fn.restype = U64 funcs[name] = fn if not prefix: - for helper in ("native_host_features", "native_rdtscp_aux"): + for helper in ("native_host_features", "native_rdtscp_aux", "native_with_fsbase"): fn = getattr(lib, helper) fn.argtypes = [U64, U64, U64] fn.restype = U64 @@ -98,6 +86,10 @@ def bind_lib(dll_path, prefix=""): return lib, funcs +def fn_address(fn): + return ctypes.cast(fn, ctypes.c_void_p).value + + def logical_cpus(): kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) kernel32.GetCurrentProcess.restype = ctypes.c_void_p @@ -136,6 +128,7 @@ def verify_exports(native_fns, target_fns, label, cpus): kernel32, full_mask, _ = logical_cpus() saved_affinity = None total_checks = 0 + with_fsbase = native_fns["native_with_fsbase"] try: for cpu in cpus: prev = pin_to_cpu(kernel32, cpu) @@ -164,43 +157,21 @@ def verify_exports(native_fns, target_fns, label, cpus): ) total_checks += 4 - # 2) Canonical FS/GS round-trips (preserving TEB GS_BASE & FS_BASE across every call) + # 2) Non-zero canonical FS_BASE values via native-only harness (restoring FS_BASE) for tag, fns in (("native", native_fns), (label, target_fns)): - for val in WR32_VALUES: - got_fs = fns["wrfsbase_32_roundtrip"](val, 0, 0) - got_gs = fns["wrgsbase_32_roundtrip"](val, 0, 0) - want = val & MASK32 - if got_fs != want or got_gs != want: - raise AssertionError( - f"{tag} wr*base_32({val:#x}): got fs={got_fs:#x}, gs={got_gs:#x}, want={want:#x}" - ) - if native_fns["rdfsbase_64"](0, 0, 0) != base_fs or native_fns["rdgsbase_64"](0, 0, 0) != base_gs: - raise AssertionError(f"{tag} wr*base_32 failed to restore FS_BASE/TEB GS_BASE") - total_checks += 2 - + fn64 = fn_address(fns["rdfsbase_64"]) + fn32 = fn_address(fns["rdfsbase_32"]) for val in CANONICAL_64_VALUES: - got_fs = fns["wrfsbase_64_roundtrip"](val, 0, 0) - got_gs = fns["wrgsbase_64_roundtrip"](val, 0, 0) - if got_fs != val or got_gs != val: + got64 = with_fsbase(val, fn64, 0) + got32 = with_fsbase(val, fn32, 0) + if got64 != val or got32 != (val & MASK32): raise AssertionError( - f"{tag} wr*base_64({val:#x}): got fs={got_fs:#x}, gs={got_gs:#x}" + f"{tag} rdfsbase with fs_base={val:#x}: got64={got64:#x}, got32={got32:#x}" ) - if native_fns["rdfsbase_64"](0, 0, 0) != base_fs or native_fns["rdgsbase_64"](0, 0, 0) != base_gs: - raise AssertionError(f"{tag} wr*base_64 failed to restore FS_BASE/TEB GS_BASE") + if native_fns["rdfsbase_64"](0, 0, 0) != base_fs: + raise AssertionError(f"{tag} native_with_fsbase failed to restore FS_BASE") total_checks += 2 - out_nv = (U64 * 2)() - for fs_v, gs_v in zip(CANONICAL_64_VALUES, reversed(CANONICAL_64_VALUES)): - got_xor = fns["wrfsgsbase_nonvolatile"](fs_v, gs_v, ctypes.addressof(out_nv)) - if got_xor != (fs_v ^ gs_v) or out_nv[0] != fs_v or out_nv[1] != gs_v: - raise AssertionError( - f"{tag} wrfsgsbase_nonvolatile({fs_v:#x}, {gs_v:#x}): " - f"got ({got_xor:#x}, {out_nv[0]:#x}, {out_nv[1]:#x})" - ) - if native_fns["rdfsbase_64"](0, 0, 0) != base_fs or native_fns["rdgsbase_64"](0, 0, 0) != base_gs: - raise AssertionError(f"{tag} wrfsgsbase_nonvolatile failed to restore FS_BASE/TEB GS_BASE") - total_checks += 1 - # 3) RDPID cross-checked against pinned RDTSCP IA32_TSC_AUX aux = native_fns["native_rdtscp_aux"](0, 0, 0) out_pid = (U64 * 2)() @@ -214,21 +185,36 @@ def verify_exports(native_fns, target_fns, label, cpus): ) total_checks += 2 - # 4) FLAG_NEUTRAL flag preservation across all five instructions - flag_buf = ctypes.create_string_buffer(8) + # 4) Nonvolatile register reads (rbx, r12, r13) + out_nv = (U64 * 3)() + for tag, fns in (("native", native_fns), (label, target_fns)): + got_xor = fns["read_host_nonvolatile"](0, 0, ctypes.addressof(out_nv)) + if (out_nv[0] != base_fs or out_nv[1] != base_gs or out_nv[2] != aux + or got_xor != (base_fs ^ base_gs ^ aux)): + raise AssertionError( + f"{tag} read_host_nonvolatile mismatch on cpu {cpu}: " + f"got ({got_xor:#x}, {out_nv[0]:#x}, {out_nv[1]:#x}, {out_nv[2]:#x})" + ) + total_checks += 1 + + # 5) FLAG_NEUTRAL flag preservation across RDFSBASE, RDGSBASE, RDPID + flag_buf = ctypes.create_string_buffer(32) for tag, fns in (("native", native_fns), (label, target_fns)): for a, b in FLAG_PAIRS: exp_sum, exp_flags = expected_add_flags(a, b) got_sum = fns["flag_preserve_fsgsbase_rdpid"](a, b, ctypes.addressof(flag_buf)) got_flags = flag_buf.raw[:5] - if got_sum != exp_sum or got_flags != exp_flags: + got_fs, got_gs, got_pid = (U64 * 3).from_buffer_copy(flag_buf.raw[8:32]) + if (got_sum != exp_sum or got_flags != exp_flags + or got_fs != base_fs or got_gs != base_gs or got_pid != aux): raise AssertionError( f"{tag} flag_preserve({a:#x}, {b:#x}): " - f"sum={got_sum:#x}!={exp_sum:#x}, flags={got_flags.hex()}!={exp_flags.hex()}" + f"sum={got_sum:#x}!={exp_sum:#x}, flags={got_flags.hex()}!={exp_flags.hex()}, " + f"reads=({got_fs:#x}, {got_gs:#x}, {got_pid:#x})" ) total_checks += 1 - # 5) Unused host-CPU reads must still compile and return 42 + # 6) Unused host-CPU reads must still compile and return 42 for tag, fns in (("native", native_fns), (label, target_fns)): got_unused = fns["unused_host_reads"](0, 0, 0) if got_unused != 42: @@ -258,7 +244,7 @@ def compile_cpp_dll(cxx_path, cpp_path, dll_path, opt_flag="/O2"): def build_mutated_sources(base_source): - """Create four C++ mutants that each break one required semantic invariant.""" + """Create five C++ mutants that each break one required semantic invariant.""" mutants = {} # 1) Keep high 32 bits instead of zero-extending on RDFSBASE/RDGSBASE 32-bit and RDPID. @@ -276,33 +262,43 @@ def build_mutated_sources(base_source): raise AssertionError(f"keep_high32 mutant expected 2 base + >=3 pid replacements, got {n1a}, {n1b}") mutants["keep_high32"] = src_keep - # 2) Drop WRFSBASE/WRGSBASE writes (no-op). - src_drop, n2 = re.subn( - r"_write(fs|gs)base_u(32|64)\(([^;]+)\);", - r"static_cast(\3);", + # 2) Truncate 64-bit RDFSBASE/RDGSBASE to 32 bits. + src_trunc, n2 = re.subn( + r"(const volatile std::uint64_t base = _read(?:fs|gs)base_u64\(\); \w+ = )static_cast\(base\);", + r"\1static_cast(base);", base_source, ) if n2 < 4: - raise AssertionError(f"drop_wrfsgsbase mutant expected >= 4 replacements, got {n2}") - mutants["drop_wrfsgsbase"] = src_drop + raise AssertionError(f"truncate_64 mutant expected >= 4 replacements, got {n2}") + mutants["truncate_64"] = src_trunc - # 3) Constant RDPID instead of reading IA32_TSC_AUX. - src_pid, n3 = re.subn(r"_rdpid_u32\(\)", "0x13572468u", base_source) - if n3 < 2: - raise AssertionError(f"constant_rdpid mutant expected >= 2 replacements, got {n3}") + # 3) Swap FS and GS base reads. + src_swap, n3 = re.subn( + r"_read(fs|gs)base_u(32|64)\(\)", + lambda m: f"_read{'gs' if m.group(1) == 'fs' else 'fs'}base_u{m.group(2)}()", + base_source, + ) + if n3 < 6: + raise AssertionError(f"swap_fs_gs mutant expected >= 6 replacements, got {n3}") + mutants["swap_fs_gs"] = src_swap + + # 4) Constant RDPID instead of reading IA32_TSC_AUX. + src_pid, n4 = re.subn(r"_rdpid_u32\(\)", "0x13572468u", base_source) + if n4 < 2: + raise AssertionError(f"constant_rdpid mutant expected >= 2 replacements, got {n4}") mutants["constant_rdpid"] = src_pid - # 4) Clobber arithmetic flags inside lifted_flag_preserve_fsgsbase_rdpid. + # 5) Clobber arithmetic flags inside lifted_flag_preserve_fsgsbase_rdpid. marker = "lifted_flag_preserve_fsgsbase_rdpid(" head, rest = base_source.split(marker, 1) body, tail = rest.split("\n}", 1) - body_mut, n4 = re.subn( + body_mut, n5 = re.subn( r"(const volatile std::uint32_t pid = _rdpid_u32\(\);[^\n]+\n)", r"\1 fa = 0; fb = 1;\n", body, count=1, ) - if n4 != 1: + if n5 != 1: raise AssertionError("clobber_flags mutant failed to anchor on _rdpid_u32 in flag_preserve") mutants["clobber_flags"] = head + marker + body_mut + "\n}" + tail @@ -318,8 +314,8 @@ def encode_seq(*instructions): def check_rejections(native_path): - # 1) Default profile (host_cpu omitted) must refuse all five instructions. - for name in ("rdfsbase_64", "rdgsbase_64", "wrfsbase_64_roundtrip", "wrgsbase_64_roundtrip", "rdpid_64"): + # 1) Default profile (host_cpu omitted) must refuse read-only/PID instructions and writes. + for name in ("rdfsbase_64", "rdgsbase_64", "rdpid_64"): try: translate(native_path, [name]) except ValueError as exc: @@ -328,33 +324,41 @@ def check_rejections(native_path): else: raise AssertionError(f"default profile unexpectedly accepted {name}") - # 2) MASM negative exports (undefined source on WRFSBASE/WRGSBASE, RSP operand). + # 2) MASM negative exports (WRFSBASE/WRGSBASE writes and RSP operands must be refused even with host_cpu=True). masm_refusals = ( - ("neg_undef_wrfsbase", "undefined register r10"), - ("neg_undef_wrgsbase", "undefined register r11"), + ("neg_wrfsbase_32", "unsupported instruction"), + ("neg_wrfsbase_64", "unsupported instruction"), + ("neg_wrgsbase_32", "unsupported instruction"), + ("neg_wrgsbase_64", "unsupported instruction"), ("neg_rsp_rdfsbase", "rsp"), + ("neg_rsp_rdgsbase", "rsp"), ("neg_rsp_rdpid", "rsp"), ) for name, expected_reason in masm_refusals: - try: - translate(native_path, [name], host_cpu=True) - except ValueError as exc: - if expected_reason not in str(exc).lower(): - raise AssertionError(f"{name}: expected {expected_reason!r}, got {exc!r}") from exc - else: - raise AssertionError(f"{name}: translator unexpectedly accepted negative export") + for opt_in in (False, True): + if "rsp" in name and not opt_in: + continue + try: + translate(native_path, [name], host_cpu=opt_in) + except ValueError as exc: + if expected_reason not in str(exc).lower(): + raise AssertionError(f"{name} (host_cpu={opt_in}): expected {expected_reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{name} (host_cpu={opt_in}): translator unexpectedly accepted negative export") - # 3) Unit Lifter.lower rejections: host_cpu omitted, RSP/ESP, prefixes, RDPID_R32. + # 3) Unit Lifter.lower rejections: host_cpu omitted, WRFSBASE/WRGSBASE, RSP/ESP, prefixes, RDPID_R32. unit_insns = [ ("lower_default_rdfsbase", Instruction.create_reg(Code.RDFSBASE_R64, R.RAX), False, "requires host_cpu=True"), ("lower_default_rdgsbase", Instruction.create_reg(Code.RDGSBASE_R32, R.EAX), False, "requires host_cpu=True"), - ("lower_default_wrfsbase", Instruction.create_reg(Code.WRFSBASE_R64, R.RCX), False, "requires host_cpu=True"), - ("lower_default_wrgsbase", Instruction.create_reg(Code.WRGSBASE_R32, R.ECX), False, "requires host_cpu=True"), ("lower_default_rdpid", Instruction.create_reg(Code.RDPID_R64, R.RAX), False, "requires host_cpu=True"), + ("lower_default_wrfsbase_64", Instruction.create_reg(Code.WRFSBASE_R64, R.RCX), False, "unsupported instruction"), + ("lower_default_wrgsbase_32", Instruction.create_reg(Code.WRGSBASE_R32, R.ECX), False, "unsupported instruction"), + ("lower_host_wrfsbase_32", Instruction.create_reg(Code.WRFSBASE_R32, R.ECX), True, "unsupported instruction"), + ("lower_host_wrfsbase_64", Instruction.create_reg(Code.WRFSBASE_R64, R.RCX), True, "unsupported instruction"), + ("lower_host_wrgsbase_32", Instruction.create_reg(Code.WRGSBASE_R32, R.ECX), True, "unsupported instruction"), + ("lower_host_wrgsbase_64", Instruction.create_reg(Code.WRGSBASE_R64, R.RCX), True, "unsupported instruction"), ("lower_rsp_rdfsbase", Instruction.create_reg(Code.RDFSBASE_R64, R.RSP), True, "unsupported use of rsp"), ("lower_esp_rdgsbase", Instruction.create_reg(Code.RDGSBASE_R32, R.ESP), True, "unsupported use of rsp"), - ("lower_rsp_wrfsbase", Instruction.create_reg(Code.WRFSBASE_R64, R.RSP), True, "unsupported use of rsp"), - ("lower_esp_wrgsbase", Instruction.create_reg(Code.WRGSBASE_R32, R.ESP), True, "unsupported use of rsp"), ("lower_rsp_rdpid", Instruction.create_reg(Code.RDPID_R64, R.RSP), True, "unsupported use of rsp"), ("lower_rdpid_r32", Instruction.create_reg(Code.RDPID_R32, R.EAX), True, "unsupported RDPID encoding"), ] @@ -367,19 +371,19 @@ def check_rejections(native_path): else: raise AssertionError(f"{label}: Lifter.lower unexpectedly accepted {ins}") - # Segment / REP / LOCK prefixes on FSGSBASE and RDPID. + # Segment / REP / LOCK prefixes on RDFSBASE, RDGSBASE, and RDPID. gs_rdfsbase = Instruction.create_reg(Code.RDFSBASE_R32, R.EAX) gs_rdfsbase.segment_prefix = R.GS gs_rdpid = Instruction.create_reg(Code.RDPID_R64, R.RAX) gs_rdpid.segment_prefix = R.GS - rep_wrfsbase = Instruction.create_reg(Code.WRFSBASE_R64, R.RCX) - rep_wrfsbase.has_rep_prefix = True + rep_rdfsbase = Instruction.create_reg(Code.RDFSBASE_R64, R.RAX) + rep_rdfsbase.has_rep_prefix = True repne_rdgsbase = Instruction.create_reg(Code.RDGSBASE_R64, R.RAX) repne_rdgsbase.has_repne_prefix = True for label, ins in ( ("seg_rdfsbase", gs_rdfsbase), ("seg_rdpid", gs_rdpid), - ("rep_wrfsbase", rep_wrfsbase), + ("rep_rdfsbase", rep_rdfsbase), ("repne_rdgsbase", repne_rdgsbase), ): try: @@ -390,10 +394,10 @@ def check_rejections(native_path): else: raise AssertionError(f"{label}: Lifter.lower unexpectedly accepted prefixed {ins}") - # 4) End-to-end PE-patched DLL rejections (patching wrfsgsbase_nonvolatile). + # 4) End-to-end PE-patched DLL rejections (patching read_host_nonvolatile). pe_bytes = Path(native_path).read_bytes() with pefile.PE(data=pe_bytes, fast_load=True) as pe: - entry = export_rva(pe, "wrfsgsbase_nonvolatile") + entry = export_rva(pe, "read_host_nonvolatile") file_off = pe.get_offset_from_rva(entry) pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] records = pe.get_data(pdata.VirtualAddress, pdata.Size) @@ -410,7 +414,10 @@ def check_rejections(native_path): ("pe_lock_rdfsbase", bytes.fromhex("f0f30faec0") + ret_bytes, "invalid"), ("pe_rsp_rdfsbase", bytes.fromhex("f3480faec4") + ret_bytes, "frame"), ("pe_rsp_rdpid", bytes.fromhex("f30fc7fc") + ret_bytes, "frame"), - ("pe_undef_wrfsbase", bytes.fromhex("f3490faed2") + ret_bytes, "undefined register"), + ("pe_wrfsbase_32", bytes.fromhex("f30faed1") + ret_bytes, "unsupported instruction"), + ("pe_wrfsbase_64", bytes.fromhex("f3480faed1") + ret_bytes, "unsupported instruction"), + ("pe_wrgsbase_32", bytes.fromhex("f30faed9") + ret_bytes, "unsupported instruction"), + ("pe_wrgsbase_64", bytes.fromhex("f3480faed9") + ret_bytes, "unsupported instruction"), ] with TemporaryDirectory() as folder: patched_path = Path(folder) / "patched.dll" @@ -422,14 +429,14 @@ def check_rejections(native_path): damaged[pdata_end_off:pdata_end_off + 4] = (entry + len(patch)).to_bytes(4, "little") patched_path.write_bytes(damaged) try: - translate(patched_path, ["wrfsgsbase_nonvolatile"], host_cpu=True) + translate(patched_path, ["read_host_nonvolatile"], host_cpu=True) except ValueError as exc: if reason not in str(exc).lower(): raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc else: raise AssertionError(f"{label}: PE translate unexpectedly accepted patched bytes") - print(f"20 unit rejections (5 default-profile, 4 MASM negative, 11 Lifter.lower/prefix) " + print(f"unit rejections (3 default-profile, 7 MASM negative, 17 Lifter.lower/prefix) " f"and {len(pe_patches)} PE-patched rejections passed") @@ -476,7 +483,7 @@ def main(): checked_cmake = verify_exports(native_fns, lifted_fns, "lifted_cmake", cpus) - # Also build /O2 and the 4 mutated C++ negative control DLLs directly from cpu_switch_aot. + # Also build /O2 and the 5 mutated C++ negative control DLLs directly from cpu_switch_aot. source_text, _ = translate(native_path, list(TRANSLATED_EXPORTS), host_cpu=True) mutants = build_mutated_sources(source_text) with TemporaryDirectory() as folder: @@ -512,7 +519,7 @@ def main(): check_rejections(native_path) record_covered_forms(native_path) print(f"verified {checked_cmake} CMake-lifted + {checked_o2} /O2-lifted checks across " - f"{len(cpus)} pinned CPU(s), 4 mutated-C++ controls, and all rejections") + f"{len(cpus)} pinned CPU(s), 5 mutated-C++ controls, and all rejections") if __name__ == "__main__": diff --git a/tools/cpu_switch_aot.py b/tools/cpu_switch_aot.py index 08fdfe978..49f92727b 100644 --- a/tools/cpu_switch_aot.py +++ b/tools/cpu_switch_aot.py @@ -249,16 +249,12 @@ # which only read them. FLAG_NEUTRAL = {M.CLZERO, M.MOV, M.MOVZX, M.MOVSX, M.MOVSXD, M.LEA, M.NOP, M.NOT, M.BSWAP, *SETCC, *CMOVCC, *SIGN_EXTENSIONS, M.MOVSB, M.MOVSW, M.MOVSD, M.MOVSQ, M.STOSB, M.STOSW, M.STOSD, M.STOSQ, M.CLD, M.STD, M.LEAVE, - M.RDFSBASE, M.RDGSBASE, M.WRFSBASE, M.WRGSBASE, M.RDPID} -HOST_CPU_FSGSBASE_CODES = { - Code.RDFSBASE_R32: ("_readfsbase_u32", False, 4), - Code.RDFSBASE_R64: ("_readfsbase_u64", False, 8), - Code.RDGSBASE_R32: ("_readgsbase_u32", False, 4), - Code.RDGSBASE_R64: ("_readgsbase_u64", False, 8), - Code.WRFSBASE_R32: ("_writefsbase_u32", True, 4), - Code.WRFSBASE_R64: ("_writefsbase_u64", True, 8), - Code.WRGSBASE_R32: ("_writegsbase_u32", True, 4), - Code.WRGSBASE_R64: ("_writegsbase_u64", True, 8), + M.RDFSBASE, M.RDGSBASE, M.RDPID} +HOST_CPU_READ_BASE_CODES = { + Code.RDFSBASE_R32: ("_readfsbase_u32", 4), + Code.RDFSBASE_R64: ("_readfsbase_u64", 8), + Code.RDGSBASE_R32: ("_readgsbase_u32", 4), + Code.RDGSBASE_R64: ("_readgsbase_u64", 8), } FLAG_PRODUCERS = {*ALU, M.CMP, M.TEST, M.INC, M.DEC, M.NEG, *SHIFTS, *BIT_TESTS, *BIT_COUNTS, *BIT_SCANS} MAX_FLAG_DISTANCE = 16 @@ -1118,7 +1114,7 @@ def lower(self, ins, sets_flags=False, producer=None): # even when a following iteration or caller overwrites the same line. return (f"{{ auto* line = reinterpret_cast({address} & ~63ull); " "for (unsigned i = 0; i < 64; ++i) line[i] = 0; }", {R.RAX: 8}, {}) - if mnemonic in (M.RDFSBASE, M.RDGSBASE, M.WRFSBASE, M.WRGSBASE, M.RDPID): + if mnemonic in (M.RDFSBASE, M.RDGSBASE, M.RDPID): if not self.host_cpu: raise ValueError(f"{str(ins).split()[0].upper()} requires host_cpu=True (--host-cpu) at RVA {ins.ip:#x}") if (ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix @@ -1134,15 +1130,9 @@ def lower(self, ins, sets_flags=False, producer=None): raise ValueError(f"unsupported RDPID encoding at RVA {ins.ip:#x}: {ins}") line = f"{{ const volatile std::uint32_t pid = _rdpid_u32(); {self.write(ins, 8, 'pid')} }}" return line, {}, {full(dest_reg): 8} - if ins.code not in HOST_CPU_FSGSBASE_CODES: + if ins.code not in HOST_CPU_READ_BASE_CODES: raise ValueError(f"unsupported FSGSBASE encoding at RVA {ins.ip:#x}: {ins}") - intrinsic, is_write, op_width = HOST_CPU_FSGSBASE_CODES[ins.code] - if is_write: - val = self.reg(dest_reg) - line = (f"{{ std::atomic_signal_fence(std::memory_order_seq_cst); " - f"{intrinsic}({val}); " - f"std::atomic_signal_fence(std::memory_order_seq_cst); }}") - return line, {full(dest_reg): op_width}, {} + intrinsic, op_width = HOST_CPU_READ_BASE_CODES[ins.code] u = unsigned(op_width) line = f"{{ const volatile {u} base = {intrinsic}(); {self.write(ins, op_width, 'base')} }}" return line, {}, {full(dest_reg): op_width} @@ -2099,8 +2089,7 @@ def lift_function(program, entry, symbol, arguments, internal): return "\n".join(source), function -PRELUDE = """#include -#include +PRELUDE = """#include #include #include #include @@ -2422,7 +2411,7 @@ def translate(image, names, bindings=None, *, image_data=False, binding=None, ho "fourth integer argument in R9, and the host must pass four") parser.add_argument("output", type=Path) parser.add_argument("--host-cpu", action="store_true", - help="opt into host-CPU instructions (rdfsbase, rdgsbase, wrfsbase, wrgsbase, rdpid)") + help="opt into read-only host-CPU instructions (rdfsbase, rdgsbase, rdpid)") parser.add_argument("--image-data", action="store_true", help="translate RIP-relative data against a live mapping of the image that the host " "binds at run time with lifted_bind_image; the generated source states the contract") From 3ed5928a0f7566820c4044b0fbca5d6c53d45fb5 Mon Sep 17 00:00:00 2001 From: ammar Date: Tue, 24 Nov 2026 14:32:59 +0200 Subject: [PATCH 104/775] runtime: verify local_log env_on, logf, and page probes without GPU --- CMakeLists.txt | 7 + docs/startup-runtime.md | 16 ++ tests/startup_local_log_check.cpp | 305 ++++++++++++++++++++++++++++++ 3 files changed, 328 insertions(+) create mode 100644 tests/startup_local_log_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ac9066e87..e525c5cd1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -746,6 +746,13 @@ add_executable(startup_logical_view_table_check tests/startup_logical_view_table target_include_directories(startup_logical_view_table_check PRIVATE src) target_compile_features(startup_logical_view_table_check PRIVATE cxx_std_17) add_test(NAME startup_logical_view_table COMMAND startup_logical_view_table_check) +# Local switch, logging, and page-probe helpers (src/startup_stubs/local_log.h, #1149). +add_executable(startup_local_log_check tests/startup_local_log_check.cpp) +target_include_directories(startup_local_log_check PRIVATE src) +target_compile_features(startup_local_log_check PRIVATE cxx_std_17) +add_test(NAME startup_local_log COMMAND startup_local_log_check) +add_test(NAME startup_local_log_guard_drop_control COMMAND startup_local_log_check --mutate guard-drop) +set_tests_properties(startup_local_log_guard_drop_control PROPERTIES WILL_FAIL TRUE) # Colour-blend register decoding (src/startup_stubs/cb_blend.h, #1216): decoder table plus draws # compared with a CPU model of the register fields. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0ece6dc15..a8e9e9c27 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -214,6 +214,22 @@ starts a byte earlier is rejected before it copies anything. No GPU and no game ctest --preset release --no-tests=error -R '^startup_inflate$' -V ``` +## Local switches, logging, and memory probing + +`tests/startup_local_log_check.cpp` (device-free ctest `startup_local_log`, with negative +control `startup_local_log_guard_drop_control`) verifies `src/startup_stubs/local_log.h`: +`env_on` (`"1"`-only gating while preserving `GetLastError`), atomic `first_calls` countdowns, +`logf` (`GetLastError` preservation, 1533-byte payload truncation, and `X2W_TRAP_LOG` append), +`probe_readable` (invalid-pointer and zero-length refusals, multi-page reads, `PAGE_NOACCESS` / +`MEM_RESERVE` prefix truncation, and `PAGE_GUARD` re-arming verified by `VirtualQuery` and a +second probe), and `readable`/`writable` boundaries across `PAGE_READONLY`, `PAGE_READWRITE`, +`PAGE_WRITECOPY`, `PAGE_NOACCESS`, `PAGE_GUARD`, and `MEM_RESERVE`. No GPU is required: + +```powershell +cmake --build --preset dev --target startup_local_log_check +ctest --preset dev --no-tests=error -R '^startup_local_log(_guard_drop_control)?$' -V +``` + ## Switches | Variable | Effect | diff --git a/tests/startup_local_log_check.cpp b/tests/startup_local_log_check.cpp new file mode 100644 index 000000000..86cd11bf3 --- /dev/null +++ b/tests/startup_local_log_check.cpp @@ -0,0 +1,305 @@ +// Checks src/startup_stubs/local_log.h without a GPU device: GetLastError-preserving env_on +// gating, atomic first_calls countdown, logf formatting/truncation/X2W_TRAP_LOG append, +// probe_readable page truncation and PAGE_GUARD re-arming, and readable/writable boundary checks. +#include "startup_stubs/local_log.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; +int cases = 0; + +void check(bool cond, const char* name) +{ + ++cases; + if (!cond) { + std::printf("FAIL %s (GetLastError=%lu)\n", name, static_cast(GetLastError())); + std::fflush(stdout); + ++failures; + } +} + +std::string read_file_bytes(const wchar_t* path) +{ + HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return {}; + std::string out; + char buf[512]; + DWORD got = 0; + while (ReadFile(file, buf, sizeof(buf), &got, nullptr) && got > 0) { + out.append(buf, buf + got); + } + CloseHandle(file); + return out; +} + +void test_env_on() +{ + const char* const var_name = "X2W_TEST_LOCAL_LOG_SWITCH"; + + SetEnvironmentVariableA(var_name, nullptr); + SetLastError(0x12345678u); + const bool unset_res = x2w_local::env_on(var_name); + const DWORD unset_err = GetLastError(); + check(!unset_res && unset_err == 0x12345678u, "env_on unset returns false and preserves GetLastError"); + + for (const char* val : {"", "0", "2", "true", "on"}) { + SetEnvironmentVariableA(var_name, val); + SetLastError(0x0BAD0001u); + const bool res = x2w_local::env_on(var_name); + const DWORD err = GetLastError(); + check(!res && err == 0x0BAD0001u, "env_on non-1 value returns false and preserves GetLastError"); + } + + SetEnvironmentVariableA(var_name, "1"); + SetLastError(0x0CAFE002u); + const bool on_res = x2w_local::env_on(var_name); + const DWORD on_err = GetLastError(); + check(on_res && on_err == 0x0CAFE002u, "env_on '1' returns true and preserves GetLastError"); + + SetEnvironmentVariableA(var_name, nullptr); +} + +void test_first_calls() +{ + LONG counter = 0; + check(x2w_local::first_calls(counter, 3) && counter == 1, "first_calls 1/3"); + check(x2w_local::first_calls(counter, 3) && counter == 2, "first_calls 2/3"); + check(x2w_local::first_calls(counter, 3) && counter == 3, "first_calls 3/3"); + check(!x2w_local::first_calls(counter, 3) && counter == 4, "first_calls 4/3 false"); + check(!x2w_local::first_calls(counter, 3) && counter == 5, "first_calls 5/3 false"); + + LONG zero_limit = 0; + check(!x2w_local::first_calls(zero_limit, 0) && zero_limit == 1, "first_calls limit=0 false"); + + LONG neg_limit = 0; + check(!x2w_local::first_calls(neg_limit, -1) && neg_limit == 1, "first_calls limit=-1 false"); + + LONG shared = 0; + std::atomic accepted{0}; + std::vector threads; + for (int t = 0; t < 4; ++t) { + threads.emplace_back([&]() { + for (int i = 0; i < 100; ++i) { + if (x2w_local::first_calls(shared, 10)) accepted.fetch_add(1, std::memory_order_relaxed); + } + }); + } + for (auto& th : threads) th.join(); + check(shared == 400 && accepted.load(std::memory_order_relaxed) == 10, + "first_calls concurrent InterlockedIncrement exactness"); +} + +void test_logf() +{ + // Silence stderr during logf checks so the test output stays clean. + const HANDLE saved_stderr = GetStdHandle(STD_ERROR_HANDLE); + HANDLE nul_handle = CreateFileW(L"NUL", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (nul_handle != INVALID_HANDLE_VALUE) SetStdHandle(STD_ERROR_HANDLE, nul_handle); + + wchar_t prev_trap_log[MAX_PATH]{}; + const DWORD prev_len = GetEnvironmentVariableW(L"X2W_TRAP_LOG", prev_trap_log, MAX_PATH); + + wchar_t temp_dir[MAX_PATH]{}; + const DWORD dir_len = GetTempPathW(MAX_PATH, temp_dir); + check(dir_len > 0 && dir_len < MAX_PATH, "GetTempPathW succeeds"); + + wchar_t log_path[MAX_PATH]{}; + std::swprintf(log_path, MAX_PATH, L"%lsx2w_local_log_test_%lu.log", temp_dir, + static_cast(GetCurrentProcessId())); + DeleteFileW(log_path); + + SetEnvironmentVariableW(L"X2W_TRAP_LOG", nullptr); + SetLastError(0x13572468u); + x2w_local::logf("unset-path-%d", 1); + check(GetLastError() == 0x13572468u, "logf preserves GetLastError when X2W_TRAP_LOG is unset"); + + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path); + SetLastError(0x0BADF00Du); + x2w_local::logf("first-%d", 42); + check(GetLastError() == 0x0BADF00Du, "logf preserves GetLastError when X2W_TRAP_LOG is set"); + + x2w_local::logf("second-%s", "line"); + + const std::string two_lines = read_file_bytes(log_path); + check(two_lines == "first-42\r\nsecond-line\r\n", "logf appends CRLF lines to X2W_TRAP_LOG"); + + // Truncation check: line[1536] reserves 2 bytes for "\r\n" and 1 for NUL -> 1533 payload bytes. + DeleteFileW(log_path); + const std::string long_msg(2000, 'A'); + x2w_local::logf("%s", long_msg.c_str()); + const std::string truncated = read_file_bytes(log_path); + const std::string expected_truncated = std::string(1533, 'A') + "\r\n"; + check(truncated == expected_truncated, "logf truncates long messages to 1533 payload bytes + CRLF"); + + DeleteFileW(log_path); + if (prev_len > 0 && prev_len < MAX_PATH) { + SetEnvironmentVariableW(L"X2W_TRAP_LOG", prev_trap_log); + } else { + SetEnvironmentVariableW(L"X2W_TRAP_LOG", nullptr); + } + if (nul_handle != INVALID_HANDLE_VALUE) { + SetStdHandle(STD_ERROR_HANDLE, saved_stderr); + CloseHandle(nul_handle); + } +} + +void test_probe_and_access(bool guard_drop_mutate) +{ + constexpr std::size_t kPage = 0x1000; + constexpr std::size_t kPages = 4; + + void* const raw = VirtualAlloc(nullptr, kPages * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + check(raw != nullptr, "VirtualAlloc 4 pages succeeds"); + if (!raw) return; + + const auto base = reinterpret_cast(raw); + std::memset(raw, 0x5A, kPages * kPage); + + // Invalid addresses and zero-byte lengths. + check(x2w_local::probe_readable(0, 16) == 0, "probe_readable rejects null"); + check(x2w_local::probe_readable(0xFFFFu, 16) == 0, "probe_readable rejects < 0x10000"); + check(x2w_local::probe_readable(0x00007FFFFFFF0000ull, 16) == 0, "probe_readable rejects > user limit"); + check(x2w_local::probe_readable(base, 0) == 0, "probe_readable rejects 0 bytes"); + + check(!x2w_local::readable(nullptr, 1) && !x2w_local::writable(nullptr, 1), "accessible rejects null"); + const auto low_ptr = reinterpret_cast(std::uintptr_t{0xFFFF}); + const auto high_ptr = reinterpret_cast(std::uintptr_t{0x00007FFFFFFF0000ull}); + check(!x2w_local::readable(low_ptr, 1) && !x2w_local::writable(low_ptr, 1), "accessible rejects < 0x10000"); + check(!x2w_local::readable(high_ptr, 1) && !x2w_local::writable(high_ptr, 1), "accessible rejects > user limit"); + check(!x2w_local::readable(raw, 0) && !x2w_local::writable(raw, 0), "accessible rejects 0 bytes"); + + // Multi-page readable range and unaligned slice. + check(x2w_local::probe_readable(base, kPages * kPage) == kPages * kPage, "probe_readable full 4 pages"); + check(x2w_local::probe_readable(base + 0xF00u, 0x2200u) == 0x2200u, "probe_readable unaligned across pages"); + check(x2w_local::readable(raw, kPages * kPage) && x2w_local::writable(raw, kPages * kPage), + "4-page RW region is readable and writable"); + + // PAGE_READONLY on page 1: readable across page 0 -> page 1, writable stops at page 0 end. + DWORD old_prot = 0; + check(VirtualProtect(reinterpret_cast(base + kPage), kPage, PAGE_READONLY, &old_prot) != 0, + "VirtualProtect page 1 PAGE_READONLY"); + check(x2w_local::readable(reinterpret_cast(base + kPage), kPage), "PAGE_READONLY is readable"); + check(!x2w_local::writable(reinterpret_cast(base + kPage), 1), "PAGE_READONLY is not writable"); + check(x2w_local::readable(reinterpret_cast(base + 0xFF0u), 32), + "readable crosses RW->RO page boundary"); + check(x2w_local::writable(reinterpret_cast(base + 0xFF0u), 16), + "writable accepts up to RW region end"); + check(!x2w_local::writable(reinterpret_cast(base + 0xFF0u), 17), + "writable rejects crossing RW->RO region boundary"); + + // PAGE_WRITECOPY via a section copy-on-write mapping: both readable and writable. + HANDLE cow_map = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, static_cast(kPage), nullptr); + check(cow_map != nullptr, "CreateFileMappingW for PAGE_WRITECOPY succeeds"); + if (cow_map) { + void* const cow_view = MapViewOfFile(cow_map, FILE_MAP_COPY, 0, 0, kPage); + check(cow_view != nullptr, "MapViewOfFile FILE_MAP_COPY succeeds"); + if (cow_view) { + MEMORY_BASIC_INFORMATION cow_mbi{}; + check(VirtualQuery(cow_view, &cow_mbi, sizeof(cow_mbi)) != 0 && + (cow_mbi.Protect & 0xFF) == PAGE_WRITECOPY, + "MapViewOfFile FILE_MAP_COPY has PAGE_WRITECOPY protection"); + check(x2w_local::readable(cow_view, kPage), "PAGE_WRITECOPY is readable"); + check(x2w_local::writable(cow_view, kPage), "PAGE_WRITECOPY is writable"); + UnmapViewOfFile(cow_view); + } + CloseHandle(cow_map); + } + + // PAGE_NOACCESS on page 2: truncates probe_readable prefix cleanly. + check(VirtualProtect(reinterpret_cast(base + 2 * kPage), kPage, PAGE_NOACCESS, &old_prot) != 0, + "VirtualProtect page 2 PAGE_NOACCESS"); + check(x2w_local::probe_readable(base, kPages * kPage) == 2 * kPage, + "probe_readable truncates before PAGE_NOACCESS"); + check(x2w_local::probe_readable(base + 0x123u, kPages * kPage - 0x123u) == 2 * kPage - 0x123u, + "probe_readable unaligned truncates before PAGE_NOACCESS"); + check(x2w_local::probe_readable(base + 2 * kPage, kPage) == 0, + "probe_readable on PAGE_NOACCESS returns 0"); + check(!x2w_local::readable(reinterpret_cast(base + 2 * kPage), 1) && + !x2w_local::writable(reinterpret_cast(base + 2 * kPage), 1), + "PAGE_NOACCESS is neither readable nor writable"); + check(!x2w_local::readable(reinterpret_cast(base + 2 * kPage - 16), 17), + "readable rejects crossing into PAGE_NOACCESS"); + + // PAGE_GUARD on page 1: probe stops before guard page and re-arms PAGE_GUARD. + check(VirtualProtect(reinterpret_cast(base + kPage), kPage, PAGE_READWRITE | PAGE_GUARD, &old_prot) != 0, + "VirtualProtect page 1 PAGE_GUARD"); + check(x2w_local::probe_readable(base, 2 * kPage) == kPage, + "probe_readable stops at PAGE_GUARD page"); + MEMORY_BASIC_INFORMATION mbi{}; + check(VirtualQuery(reinterpret_cast(base + kPage), &mbi, sizeof(mbi)) != 0, + "VirtualQuery after first PAGE_GUARD probe"); + if (guard_drop_mutate) { + check((mbi.Protect & PAGE_GUARD) == 0, "guard-drop control expects PAGE_GUARD cleared"); + } else { + check((mbi.Protect & PAGE_GUARD) != 0, "probe_readable re-arms PAGE_GUARD after trip"); + // Second probe must hit the re-armed guard page at the same offset and keep it armed. + check(x2w_local::probe_readable(base, 2 * kPage) == kPage, + "second probe_readable still stops at re-armed PAGE_GUARD"); + MEMORY_BASIC_INFORMATION mbi2{}; + check(VirtualQuery(reinterpret_cast(base + kPage), &mbi2, sizeof(mbi2)) != 0 && + (mbi2.Protect & PAGE_GUARD) != 0, + "second probe_readable keeps PAGE_GUARD armed"); + check(!x2w_local::readable(reinterpret_cast(base + kPage + 0x10u), 16), + "readable returns false on PAGE_GUARD"); + check(!x2w_local::writable(reinterpret_cast(base + kPage), 16), + "writable returns false on PAGE_GUARD"); + MEMORY_BASIC_INFORMATION mbi3{}; + check(VirtualQuery(reinterpret_cast(base + kPage), &mbi3, sizeof(mbi3)) != 0 && + (mbi3.Protect & PAGE_GUARD) != 0, + "readable/writable keeps PAGE_GUARD armed"); + } + + VirtualFree(raw, 0, MEM_RELEASE); + + // MEM_RESERVE (uncommitted) tail boundary. + void* const reserved = VirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE, PAGE_READWRITE); + check(reserved != nullptr, "VirtualAlloc MEM_RESERVE 2 pages succeeds"); + if (reserved) { + void* const first_committed = VirtualAlloc(reserved, kPage, MEM_COMMIT, PAGE_READWRITE); + check(first_committed == reserved, "commit first page of reserved range"); + const auto rbase = reinterpret_cast(reserved); + check(x2w_local::probe_readable(rbase, 2 * kPage) == kPage, + "probe_readable truncates before MEM_RESERVE"); + check(x2w_local::readable(reserved, kPage) && x2w_local::writable(reserved, kPage), + "committed head of reserved range is readable and writable"); + check(!x2w_local::readable(reinterpret_cast(rbase + kPage), 1) && + !x2w_local::writable(reinterpret_cast(rbase + kPage), 1), + "MEM_RESERVE page is neither readable nor writable"); + VirtualFree(reserved, 0, MEM_RELEASE); + } +} + +} // namespace + +int main(int argc, char** argv) +{ + // --mutate guard-drop: negative control expecting PAGE_GUARD to be dropped rather than re-armed. + const bool guard_drop_mutate = + argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "guard-drop") == 0; + if (argc > 1 && !guard_drop_mutate) { + std::printf("unknown mutation\n"); + return 2; + } + + test_env_on(); + test_first_calls(); + test_logf(); + test_probe_and_access(guard_drop_mutate); + + if (failures) { + std::printf("startup_local_log: %d of %d FAILED\n", failures, cases); + return 1; + } + std::printf("startup_local_log: PASS (%d cases)\n", cases); + return 0; +} From ecf042f578f34ce017800ee388d369ff57bd3642 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:33:30 +0100 Subject: [PATCH 105/775] runtime: complete the failed DirectStorage suffix only after the worker finished the submitted prefix --- src/startup_stubs/xcrdapi.cpp | 24 ++++++- tests/startup_storage_worker_start.cpp | 99 ++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 3 deletions(-) diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index a444fdd63..7793aa2bc 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -92,6 +92,9 @@ struct QueueWork { std::mutex mutex; std::condition_variable wake; std::deque waiting, submitted; + std::condition_variable drained; // signaled when the worker finishes an entry + u64 submitted_total = 0; // entries ever moved to `submitted`, guarded by mutex + u64 finished_total = 0; // entries the worker has finished running, guarded by mutex bool worker_started = false; // guarded by the setup mutex u64 next_entry_id = 0; u64 next_submission_id = 0; @@ -637,8 +640,11 @@ void fail_entry(Object* self, const Entry& entry, const char* reason) noexcept entry.type == Entry::request ? *reinterpret_cast(entry.bytes) : 0ull); } +thread_local bool on_queue_worker = false; // Submit from a worker must not wait for itself + DWORD WINAPI queue_worker(void* parameter) { + on_queue_worker = true; auto* const self = static_cast(parameter); QueueWork& work = *self->work; for (;;) { @@ -674,7 +680,9 @@ DWORD WINAPI queue_worker(void* parameter) if (work.submitted.empty()) { work.cached_streams.clear(); } + ++work.finished_total; } + work.drained.notify_all(); } } @@ -765,9 +773,8 @@ void fail_unstarted(Object* self, Entry::Type type, Object* array, unsigned inde // deferred, every later entry until the next Submit is deferred too, even if it could be stored: // the stored entries (`waiting`) are an in-order prefix and the deferred ones an in-order suffix. // Submit handles the prefix first (moves it to the worker, or fails it), then fails the suffix. -// Limitation: when the prefix runs on the worker, a status entry in the suffix fails synchronously -// inside Submit and cannot see a failure the worker finds later in the prefix; the next status entry -// will. After the first allocation failure the rest of the batch fails with E_OUTOFMEMORY even if +// When the prefix runs on the worker, Submit waits for the worker to finish it before it fails the +// suffix, so suffix completions are visible in queue order and see the prefix's failures. After the first allocation failure the rest of the batch fails with E_OUTOFMEMORY even if // memory has recovered, which is acceptable under out-of-memory and preferable to reordering. bool has_unrecorded(Object* self) { @@ -837,6 +844,7 @@ void submit(Object* self) return; } bool all_moved = true; + u64 prefix_end = 0; { const std::lock_guard guard(work->mutex); const u64 submission_id = ++work->next_submission_id; @@ -846,13 +854,23 @@ void submit(Object* self) Entry& entry = work->waiting.front(); entry.submission_id = submission_id; work->submitted.push_back(std::move(entry)); + ++work->submitted_total; work->waiting.pop_front(); } } catch (const std::bad_alloc&) { all_moved = false; } + prefix_end = work->submitted_total; } work->wake.notify_one(); + // Entries completed here (the rest of `waiting`, the suffix) come after the prefix on the worker, so + // they wait until the worker has finished that prefix: a status entry or fence then cannot complete + // ahead of an earlier request, and cannot consume the pending failure before the worker reports it. + // Nothing allocates, and nothing waits when there is nothing to complete here. + if ((!all_moved || has_unrecorded(self)) && !on_queue_worker) { + std::unique_lock lock(work->mutex); + work->drained.wait(lock, [&] { return work->finished_total >= prefix_end; }); + } if (!all_moved) fail_waiting(self, work); fail_unrecorded(self); } diff --git a/tests/startup_storage_worker_start.cpp b/tests/startup_storage_worker_start.cpp index c46c4b101..288343a08 100644 --- a/tests/startup_storage_worker_start.cpp +++ b/tests/startup_storage_worker_start.cpp @@ -548,6 +548,104 @@ bool entries_keep_their_order(Fixture& f) return true; } +// Suffix completions are serialized behind the submitted prefix. The prefix is one fence signal that the +// control holds at an event (inside the worker); the suffix is a status entry and a second fence whose +// storage failed at Enqueue. While the prefix is held Submit must not complete either of them; after +// the release the prefix fence, the status entry and the suffix fence become visible in queue order. +struct HoldFence { + void** vtable; + std::atomic signals{0}; + std::atomic order{0}; +}; +std::atomic completion_counter{0}; +HANDLE hold_entered = nullptr; +HANDLE hold_release = nullptr; +bool hold_prefix = false; + +long __stdcall held_signal(void* self, std::uint64_t) +{ + auto* fence = static_cast(self); + if (hold_prefix) { + SetEvent(hold_entered); + WaitForSingleObject(hold_release, completion_timeout_ms); + } + fence->order = ++completion_counter; + ++fence->signals; + return 0; +} + +struct SubmitThread { + Fixture* f; + Fixture::Queue* q; + static DWORD WINAPI run(void* parameter) + { + auto* self = static_cast(parameter); + self->f->submit(*self->q); + return 0; + } +}; + +bool suffix_waits_for_prefix(Fixture& f) +{ + void* hold_vtable[11] = {}; + hold_vtable[10] = reinterpret_cast(&held_signal); + hold_entered = CreateEventW(nullptr, TRUE, FALSE, nullptr); + hold_release = CreateEventW(nullptr, TRUE, FALSE, nullptr); + int suffix_cases = 0; + for (int fail_nth = 1; fail_nth <= 14; ++fail_nth) { + sweep_name = "suffix_order"; + sweep_n = fail_nth; + sweep_m = 0; + Fixture::Queue q; + if (!f.create(q, f.vtables)) return fail("cannot create the queue"); + HoldFence prefix_fence, suffix_fence; + prefix_fence.vtable = hold_vtable; + suffix_fence.vtable = hold_vtable; + ResetEvent(hold_entered); + ResetEvent(hold_release); + hold_prefix = false; + try { + arm(fail_nth); + reinterpret_cast(q.queue->vtable[5])(q.queue, &prefix_fence, 1); + f.status_entry(q, 0); + reinterpret_cast(q.queue->vtable[5])(q.queue, &suffix_fence, 2); + disarm(); + } catch (...) { + disarm(); + return fail("an exception left an Enqueue call"); + } + // Only the runs where an entry after the first one lost its place in the queue list are a suffix. + if (!q.queue->work || q.queue->work->waiting.empty() || !has_unrecorded(q.queue)) { + hold_prefix = false; + f.submit(q); + continue; + } + ++suffix_cases; + completion_counter = 0; + hold_prefix = true; + SubmitThread submitter{&f, &q}; + HANDLE thread = CreateThread(nullptr, 0, SubmitThread::run, &submitter, 0, nullptr); + if (!thread) return fail("cannot start the Submit thread"); + const bool held = WaitForSingleObject(hold_entered, completion_timeout_ms) == WAIT_OBJECT_0; + if (held) Sleep(200); // time for a Submit that does not wait to complete the suffix + const bool early = f.complete(q, 0) || suffix_fence.signals != 0; + SetEvent(hold_release); + WaitForSingleObject(thread, completion_timeout_ms); + CloseHandle(thread); + hold_prefix = false; + if (!held) return fail("the worker never reached the held prefix fence"); + if (early) return fail("a status entry or fence of the failed suffix completed before the held prefix"); + if (!f.complete(q, 0) || prefix_fence.signals != 1 || suffix_fence.signals != 1) + return fail("the prefix and the suffix did not both complete"); + if (prefix_fence.order >= suffix_fence.order) return fail("the suffix fence was signaled before the prefix fence"); + } + CloseHandle(hold_entered); + CloseHandle(hold_release); + if (suffix_cases == 0) return fail("the control never produced a failed suffix behind a submitted prefix"); + std::printf("suffix completes behind the prefix: %d cases\n", suffix_cases); + return true; +} + // A crash is never silent: whatever ends the process names the stage it was in. const char* volatile current_stage = "start"; @@ -668,6 +766,7 @@ int main() if (!stage("every_allocation_on_every_thread_can_fail", every_allocation_on_every_thread_can_fail, f)) return 1; if (!stage("page_tokens_allocation_fails", page_tokens_allocation_fails, f)) return 1; if (!stage("entries_keep_their_order", entries_keep_their_order, f)) return 1; + if (!stage("suffix_waits_for_prefix", suffix_waits_for_prefix, f)) return 1; std::puts("a queue that cannot start its worker or allocate completes status and fences at Submit, and recovers"); return 0; } From d0b04e858d1f02f0ae6c2d5b556a851c0e985ddd Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 12:55:18 +0100 Subject: [PATCH 106/775] startup: add storage fallback, stale cache warning and fast-fail diagnostics in launch.py --- docs/startup-runtime.md | 6 +- tests/startup_launch_check.py | 121 ++++++++++++++++++++++++++++++++-- tools/startup/launch.py | 53 ++++++++++++++- 3 files changed, 169 insertions(+), 11 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0ece6dc15..41e0d446b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -191,7 +191,11 @@ adds memory dumps to the stop report. source-built `tests/startup_launch_probe.cpp`. A finished run reports the child's exit code and saves its stdout, stderr and trap log; a child that outlives `--timeout` is terminated; `--memory-gib` and `--max-processes` stop an over-limit allocation and a helper process, and the same requests succeed -under larger limits; a missing executable is reported instead of looking like a finished run. No GPU +under larger limits; a missing executable is reported instead of looking like a finished run. When +`X2W_STORAGE_PATH` is unset and `S:\` does not exist, `launch.py` creates `\storage` as a +per-run fallback (preserving `X2W_STORAGE_PATH` when set); it warns without deleting when +`X2W_SHADER_CACHE` points to a non-empty directory, and prints a fast-fail diagnostic line pointing +to `trap.log`, `X2W_STORAGE_PATH` and `X2W_SHADER_CACHE` on a sub-second non-zero exit. No GPU and no game files are needed, and the `pr` preset builds the probe and runs the test: ```powershell diff --git a/tests/startup_launch_check.py b/tests/startup_launch_check.py index 8b15e306b..23680330e 100644 --- a/tests/startup_launch_check.py +++ b/tests/startup_launch_check.py @@ -7,6 +7,7 @@ game files are involved. """ from pathlib import Path +import os import subprocess import sys import tempfile @@ -15,13 +16,16 @@ REPO = Path(__file__).resolve().parents[1] LAUNCH = REPO / "tools/startup/launch.py" +sys.path.insert(0, str(LAUNCH.parent)) +import launch as launch_mod # noqa: E402 -def launch(probe, work, name, options, arguments): + +def launch(probe, work, name, options, arguments, env=None): logdir = work / name logdir.mkdir() command = [sys.executable, "-B", str(LAUNCH), str(probe), str(work), str(logdir), *options, "--", *arguments] started = time.monotonic() - result = subprocess.run(command, capture_output=True, text=True, timeout=120) + result = subprocess.run(command, capture_output=True, text=True, timeout=120, env=env) return result, logdir, time.monotonic() - started @@ -30,25 +34,126 @@ def captured(logdir, name): return path.read_text(encoding="utf-8") if path.exists() else None +def run_unit_tests(): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + + # 1. X2W_STORAGE_PATH fallback creation when unset/empty and default missing. + logdir = root / "run_unset" + logdir.mkdir() + env = {} + msg = launch_mod.prepare_storage_path(env, str(logdir), default_storage=str(root / "missing_drive"), + exists_fn=lambda _: False) + expected_storage = str(logdir / "storage") + assert msg and expected_storage in msg, msg + assert env.get("X2W_STORAGE_PATH") == expected_storage, env + assert (logdir / "storage").is_dir() + + env_empty = {"X2W_STORAGE_PATH": " "} + logdir_empty = root / "run_empty" + logdir_empty.mkdir() + msg_empty = launch_mod.prepare_storage_path(env_empty, str(logdir_empty), exists_fn=lambda _: False) + assert msg_empty and str(logdir_empty / "storage") in msg_empty, msg_empty + assert env_empty["X2W_STORAGE_PATH"] == str(logdir_empty / "storage") + + # 2. X2W_STORAGE_PATH preservation when already set or when default drive exists. + logdir_set = root / "run_set" + logdir_set.mkdir() + custom = str(root / "custom_storage") + env_set = {"X2W_STORAGE_PATH": custom} + assert launch_mod.prepare_storage_path(env_set, str(logdir_set), exists_fn=lambda _: False) is None + assert env_set["X2W_STORAGE_PATH"] == custom + assert not (logdir_set / "storage").exists() + + logdir_default = root / "run_default" + logdir_default.mkdir() + env_default = {} + assert launch_mod.prepare_storage_path(env_default, str(logdir_default), exists_fn=lambda _: True) is None + assert "X2W_STORAGE_PATH" not in env_default + assert not (logdir_default / "storage").exists() + + # 3. Stale X2W_SHADER_CACHE warning for non-empty dir vs silence for empty/non-existent/unset. + non_empty_cache = root / "cache_non_empty" + non_empty_cache.mkdir() + cached_file = non_empty_cache / "req_abc.dxil" + cached_file.write_text("cached", encoding="utf-8") + warn = launch_mod.check_shader_cache_warning({"X2W_SHADER_CACHE": str(non_empty_cache)}) + assert warn and "stale" in warn and str(non_empty_cache) in warn, warn + assert cached_file.exists(), "shader cache check must not delete cached files" + + empty_cache = root / "cache_empty" + empty_cache.mkdir() + assert launch_mod.check_shader_cache_warning({"X2W_SHADER_CACHE": str(empty_cache)}) is None + assert launch_mod.check_shader_cache_warning({"X2W_SHADER_CACHE": str(root / "cache_missing")}) is None + assert launch_mod.check_shader_cache_warning({}) is None + + # 4. Fast-fail diagnostic emission on quick non-zero exit vs silence on zero exit or slow exit. + diag = launch_mod.format_fast_fail_diagnostic( + 7, 0.25, str(logdir / "trap.log"), + {"X2W_STORAGE_PATH": expected_storage, "X2W_SHADER_CACHE": str(non_empty_cache)}, + ) + assert diag and "0x00000007" in diag and "trap.log" in diag, diag + assert expected_storage in diag and str(non_empty_cache) in diag, diag + + assert launch_mod.format_fast_fail_diagnostic(0, 0.10, str(logdir / "trap.log"), {}) is None + assert launch_mod.format_fast_fail_diagnostic(7, 1.00, str(logdir / "trap.log"), {}) is None + assert launch_mod.format_fast_fail_diagnostic(7, 2.50, str(logdir / "trap.log"), {}) is None + + print("launch-unit: storage fallback/preservation, stale shader cache warning and fast-fail diagnostics passed") + return 0 + + def main(probe): + run_unit_tests() probe = Path(probe).resolve() with tempfile.TemporaryDirectory() as temporary: work = Path(temporary) - # A finished run: the launcher reports the child's exit code and saves both streams and the trap log. - result, logdir, _ = launch(probe, work, "report", ["--timeout", "10"], ["report", "7"]) + # A finished non-zero run in under 1 s: reports exit code, streams, trap log and fast-fail diagnostic. + base_env = {k: v for k, v in os.environ.items() if k not in ("X2W_STORAGE_PATH", "X2W_SHADER_CACHE")} + result, logdir, _ = launch(probe, work, "report", ["--timeout", "10"], ["report", "7"], env=base_env) assert result.returncode == 0, result.stderr assert "exited" in result.stdout and "exit code 0x00000007" in result.stdout, result.stdout assert "peak job memory" in result.stdout, result.stdout + assert "fast-fail:" in result.stdout and "trap.log" in result.stdout, result.stdout + assert "X2W_STORAGE_PATH=" in result.stdout and "X2W_SHADER_CACHE=" in result.stdout, result.stdout + if not os.path.exists("S:\\"): + assert "created fallback storage:" in result.stdout, result.stdout + assert (logdir / "storage").is_dir() assert captured(logdir, "stdout.txt") == "launch-probe stdout\n", captured(logdir, "stdout.txt") assert captured(logdir, "stderr.txt") == "launch-probe stderr\n", captured(logdir, "stderr.txt") assert captured(logdir, "trap.log") == "x2w-trap launch-probe\n", captured(logdir, "trap.log") - # A child that overstays the timeout is terminated, not left running. - result, logdir, elapsed = launch(probe, work, "timeout", ["--timeout", "1"], ["sleep", "30000"]) + # Quick zero exit with explicit X2W_STORAGE_PATH and empty X2W_SHADER_CACHE: no fast-fail, no fallback, no warning. + empty_cache = work / "empty_cache" + empty_cache.mkdir() + custom_storage = work / "custom_storage" + custom_storage.mkdir() + clean_env = dict(base_env, X2W_STORAGE_PATH=str(custom_storage), X2W_SHADER_CACHE=str(empty_cache)) + result, logdir, _ = launch(probe, work, "noop", ["--timeout", "10"], ["noop"], env=clean_env) + assert result.returncode == 0, result.stderr + assert "fast-fail:" not in result.stdout, result.stdout + assert "created fallback storage:" not in result.stdout, result.stdout + assert "warning: X2W_SHADER_CACHE" not in result.stdout, result.stdout + assert not (logdir / "storage").exists() + + # Non-empty X2W_SHADER_CACHE emits a warning without deleting cached files. + stale_cache = work / "stale_cache" + stale_cache.mkdir() + marker = stale_cache / "shader.dxil" + marker.write_text("dxil", encoding="utf-8") + stale_env = dict(clean_env, X2W_SHADER_CACHE=str(stale_cache)) + result, logdir, _ = launch(probe, work, "stale-cache", ["--timeout", "10"], ["noop"], env=stale_env) + assert result.returncode == 0, result.stderr + assert "warning: X2W_SHADER_CACHE" in result.stdout and "stale" in result.stdout, result.stdout + assert marker.exists() + + # A child that overstays the timeout is terminated, not left running (and >= 1 s exit is not fast-fail). + result, logdir, elapsed = launch(probe, work, "timeout", ["--timeout", "1"], ["sleep", "30000"], env=clean_env) assert result.returncode == 0, result.stderr assert "killed after 1 s timeout" in result.stdout, result.stdout assert "exit code 0xdead0001" in result.stdout, result.stdout + assert "fast-fail:" not in result.stdout, result.stdout assert elapsed < 20, f"the launcher took {elapsed:.1f} s to enforce a 1 s timeout" assert captured(logdir, "stdout.txt") == "launch-probe sleeping\n", captured(logdir, "stdout.txt") @@ -82,6 +187,8 @@ def main(probe): if __name__ == "__main__": + if len(sys.argv) == 2 and sys.argv[1] == "--unit": + sys.exit(run_unit_tests()) if len(sys.argv) != 2: - sys.exit("usage: startup_launch_check.py ") + sys.exit("usage: startup_launch_check.py | --unit") sys.exit(main(sys.argv[1])) \ No newline at end of file diff --git a/tools/startup/launch.py b/tools/startup/launch.py index 0ad57a9bf..c4a84ca45 100644 --- a/tools/startup/launch.py +++ b/tools/startup/launch.py @@ -9,7 +9,9 @@ import sys import time -k32 = ctypes.WinDLL("kernel32", use_last_error=True) +k32 = None +if hasattr(ctypes, "WinDLL"): + k32 = ctypes.WinDLL("kernel32", use_last_error=True) class STARTUPINFOW(ctypes.Structure): @@ -46,8 +48,44 @@ class SECURITY_ATTRIBUTES(ctypes.Structure): _fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", wt.BOOL)] -k32.CreateFileW.restype = wt.HANDLE -k32.CreateJobObjectW.restype = wt.HANDLE +if k32 is not None: + k32.CreateFileW.restype = wt.HANDLE + k32.CreateJobObjectW.restype = wt.HANDLE + + +def prepare_storage_path(env, logdir, default_storage="S:\\", exists_fn=os.path.exists, makedirs_fn=os.makedirs): + """Ensure X2W_STORAGE_PATH has a valid directory when unset and the default drive is absent.""" + current = env.get("X2W_STORAGE_PATH", "").strip() + if current: + return None + if exists_fn(default_storage): + return None + fallback = os.path.join(logdir, "storage") + makedirs_fn(fallback, exist_ok=True) + env["X2W_STORAGE_PATH"] = fallback + return f"X2W_STORAGE_PATH unset and {default_storage} missing; created fallback storage: {fallback}" + + +def check_shader_cache_warning(env): + """Warn if X2W_SHADER_CACHE points to an existing non-empty directory.""" + shader_cache = env.get("X2W_SHADER_CACHE", "").strip() + if not shader_cache or not os.path.isdir(shader_cache): + return None + with os.scandir(shader_cache) as entries: + if any(entries): + return (f"warning: X2W_SHADER_CACHE ({shader_cache}) is non-empty; " + "cached translated shaders from an older build may be stale") + return None + + +def format_fast_fail_diagnostic(exit_code, elapsed, trap_log, env): + """Return a concise diagnostic line when the child exits non-zero in under 1.0 second.""" + if elapsed >= 1.0 or exit_code == 0: + return None + storage = env.get("X2W_STORAGE_PATH", "").strip() or "S:\\" + shader_cache = env.get("X2W_SHADER_CACHE", "").strip() or "(unset)" + return (f"fast-fail: exited with {exit_code:#010x} in {elapsed:.2f} s (< 1.0 s); " + f"check trap log={trap_log}, X2W_STORAGE_PATH={storage}, X2W_SHADER_CACHE={shader_cache}") def inheritable_file(path): @@ -92,6 +130,12 @@ def main(): si.dwFlags = 0x100 # STARTF_USESTDHANDLES si.hStdOutput, si.hStdError = out, err env = dict(os.environ, X2W_TRAP_LOG=trap_log) + storage_note = prepare_storage_path(env, logdir) + if storage_note: + print(storage_note) + shader_warning = check_shader_cache_warning(env) + if shader_warning: + print(shader_warning) block = "".join(f"{k}={v}\0" for k, v in env.items()) + "\0" cmdline = ctypes.create_unicode_buffer(" ".join(f'"{a}"' for a in [exe, *extra])) pi = PROCESS_INFORMATION() @@ -119,6 +163,9 @@ def main(): k32.CloseHandle(wt.HANDLE(h)) print(f"pid {pi.dwProcessId} {ended} in {elapsed:.2f} s, exit code {code.value:#010x}, " f"peak job memory {info.PeakJobMemoryUsed / 2**20:.1f} MiB") + fast_fail = format_fast_fail_diagnostic(code.value, elapsed, trap_log, env) + if fast_fail: + print(fast_fail) for name in ("stdout.txt", "stderr.txt", "trap.log"): path = os.path.join(logdir, name) text = open(path, encoding="utf-8", errors="replace").read() if os.path.exists(path) else None From 2842678dad29d06996a81b3f072e776c48db888d Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:06:40 +0100 Subject: [PATCH 107/775] startup: resolve the cache check against the child cwd and keep it non-fatal --- tests/startup_launch_check.py | 15 +++++++++++++++ tools/startup/launch.py | 26 ++++++++++++++++++-------- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/tests/startup_launch_check.py b/tests/startup_launch_check.py index 23680330e..3d0df60c2 100644 --- a/tests/startup_launch_check.py +++ b/tests/startup_launch_check.py @@ -87,6 +87,21 @@ def run_unit_tests(): assert launch_mod.check_shader_cache_warning({"X2W_SHADER_CACHE": str(root / "cache_missing")}) is None assert launch_mod.check_shader_cache_warning({}) is None + # 3b. Relative cache resolves against the child cwd; unlistable cache never raises. + child = root / "child_cwd" + (child / "rel_cache").mkdir(parents=True) + (child / "rel_cache" / "req.dxil").write_text("cached", encoding="utf-8") + assert launch_mod.check_shader_cache_warning({"X2W_SHADER_CACHE": "rel_cache"}, str(child)), "relative cache not resolved against cwd" + assert launch_mod.check_shader_cache_warning({"X2W_SHADER_CACHE": "rel_cache"}, str(root)) is None + real_scandir = os.scandir + def denied(_path): + raise PermissionError("denied") + os.scandir = denied + try: + assert launch_mod.check_shader_cache_warning({"X2W_SHADER_CACHE": str(non_empty_cache)}) is None + finally: + os.scandir = real_scandir + # 4. Fast-fail diagnostic emission on quick non-zero exit vs silence on zero exit or slow exit. diag = launch_mod.format_fast_fail_diagnostic( 7, 0.25, str(logdir / "trap.log"), diff --git a/tools/startup/launch.py b/tools/startup/launch.py index c4a84ca45..9cab0c02b 100644 --- a/tools/startup/launch.py +++ b/tools/startup/launch.py @@ -66,15 +66,25 @@ def prepare_storage_path(env, logdir, default_storage="S:\\", exists_fn=os.path. return f"X2W_STORAGE_PATH unset and {default_storage} missing; created fallback storage: {fallback}" -def check_shader_cache_warning(env): - """Warn if X2W_SHADER_CACHE points to an existing non-empty directory.""" +def check_shader_cache_warning(env, cwd=None): + """Warn if X2W_SHADER_CACHE points to an existing non-empty directory. + + A relative value is resolved against the child's working directory, as the child sees it. + Inspection failures are advisory only and never stop the launch. + """ shader_cache = env.get("X2W_SHADER_CACHE", "").strip() - if not shader_cache or not os.path.isdir(shader_cache): + if not shader_cache: + return None + inspected = os.path.join(cwd, shader_cache) if cwd and not os.path.isabs(shader_cache) else shader_cache + try: + if not os.path.isdir(inspected): + return None + with os.scandir(inspected) as entries: + if any(entries): + return (f"warning: X2W_SHADER_CACHE ({shader_cache}) is non-empty; " + "cached translated shaders from an older build may be stale") + except OSError: return None - with os.scandir(shader_cache) as entries: - if any(entries): - return (f"warning: X2W_SHADER_CACHE ({shader_cache}) is non-empty; " - "cached translated shaders from an older build may be stale") return None @@ -133,7 +143,7 @@ def main(): storage_note = prepare_storage_path(env, logdir) if storage_note: print(storage_note) - shader_warning = check_shader_cache_warning(env) + shader_warning = check_shader_cache_warning(env, cwd) if shader_warning: print(shader_warning) block = "".join(f"{k}={v}\0" for k, v in env.items()) + "\0" From a8a5d992dc59bf85d5a78641863f9c9f670a60ec Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:35:19 +0800 Subject: [PATCH 108/775] docs: record the gpu alias window run on Intel Xe2 The gpu_alias measurement list records one run per commit and adapter. Add the Intel Arc 140T at 06e2ff78 for gpu_alias_window_hardware: two pages at offset\ 0x11234 over 0x1e000 bytes, relative identity and roundtrip confirmed, the negative readback unchanged, zero mismatches and zero debug errors or warnings. Docs only. --- docs/experiments.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/experiments.md b/docs/experiments.md index 471a05c73..e8e2d7b3d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6281,6 +6281,7 @@ Measured at commit `55cea41` on Windows 11 build 26300, with the debug layer una - At commit `9bdbb20` two RDNA 4 adapters give the same probe result, so `gpu_alias_lookup_writes_hardware` fails on both by design: each of the four buffers reads 256, not 64, on all three runs of each adapter. The adapters are an AMD Radeon RX 9070 XT (device `7550`, driver 32.0.32015.7029, debug layer enabled; [report](https://github.com/R0Y00/Xbox2Windows/issues/369)) and an AMD Radeon RX 9060 XT (device `7590`, driver 32.0.32029.2010, debug layer unavailable; [report](https://github.com/R0Y00/Xbox2Windows/issues/369#issuecomment-7071098620)). On both, the title-address fixture itself records zero mismatches in both groups: the add and sub words, and the 1,047 per-record results and 147,454 other words. In the same runs an NVIDIA GeForce RTX 5060 Ti (driver 32.0.16.2124) and the in-box WARP 10.0.26100.9711 and 10.0.26100.9818 read 64 in all four buffers. Local probe variants on the RX 9070 XT, not committed, isolated the condition. A resource index that varies within a wave gives 256 in every buffer, both without the returned value and when lane pairs share an index. An index that is uniform across each wave, a literal index of 0 and plain stores through `NonUniformResourceIndex` are exact. An explicit waterfall that selects the index with `WaveReadLaneFirst` and runs the atomic once per distinct index reads 64 in all four buffers. The cause is not established. - At commit `65492448` on Windows 10 22H2 (build 19045.6456, MSVC 19.44.35230.0, Windows SDK 10.0.26100.0 DXC, debug layer enabled on both backends), a GTX 1060 6 GB (driver 32.0.15.6094) reads 64 in all four probe buffers in 3/3 runs, and the in-box WARP 10.0.19041.5794 on the same host reproduces the Windows 10 behavior above: each buffer reads 256 in 3/3 runs, with the fixture reporting the shared add and sub words as the only two mismatches. Both backends matched all 1,047 per-record results and the other 147,454 words, with zero debug errors or warnings ([report](https://github.com/R0Y00/Xbox2Windows/issues/369#issuecomment-7071770464)). - At commit `185b9d6c` on Windows 11 build 26200 with the debug layer enabled, an RDNA 3 adapter reproduces the same probe failure: an AMD Radeon RX 7900 XTX (device `744c`, driver 32.0.32029.2010) reads 256 in each of the four buffers, with the title-address fixture recording zero mismatches across all 1,047 records and 147,454 checked words and zero D3D12 debug errors or warnings ([report](https://github.com/R0Y00/Xbox2Windows/issues/369)). +- At commit `06e2ff78` on Windows 11 build 26300.9974 with the debug layer enabled, an Intel Arc 140T (device `7d51`, driver 32.0.101.8132) passed `gpu_alias_window_hardware`: two pages at offset `0x11234` over `0x1e000` bytes, relative identity and roundtrip both confirmed, the negative readback unchanged and zero mismatches, with zero D3D12 debug errors or warnings. - Signed zeros in `gpu_alias_lookup_writes`. Float min and max replace only on a strict `<` or `>`, so `-0.0` and `+0.0` tie and the stored word is kept. The fixture expects this, not IEEE `minNum`/`maxNum`, and compares raw bits. Four words get one record each: min and max, each from `+0` with a `-0` candidate and from `-0` with a `+0` candidate. All four must keep their starting bits. Four more words start at a signed zero and have 256 contenders each. Every third contender alternates `-0` and `+0`, and the rest are strictly negative or strictly positive inputs. On two of these words a strictly smaller (min) or larger (max) input must win. On the other two every contender ties or loses, so the starting zero must survive. A zero that could win is never contended by the opposite zero, so every expected word is deterministic. A ninth max word has only negative contenders and is seeded at negative infinity, because under a strict `>` no negative input can replace a zero. The highest negative must win. On Windows 11 build 26300 with the debug layer enabled, WARP 10.0.26100.10068 and an NVIDIA GeForce RTX 3060 (driver 32.0.16.1742) passed in the `dev` and `release` presets: 2,331 records and 0 mismatches. An Intel UHD Graphics 770 (driver 32.0.101.7092) matched all 2,331 records and all nine signed-zero words too, but failed as before on the array-atomics probe (`256,192,128,64`, [#369](https://github.com/R0Y00/Xbox2Windows/issues/369)). Replacing on equality (`<=`/`>=`) gave 5 mismatches on both adapters, all on signed-zero words. A compare-exchange loop without retry still passed on WARP. On the RTX 3060 it failed in 3 of 3 runs with 5 mismatches: the original min and max words and the three contended words a strict input must win. - The [RX 6500 report](https://github.com/R0Y00/Xbox2Windows/pull/793) used From d037cec091af3ce5782ba640c1f45db1cd28279e Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:16:51 +0100 Subject: [PATCH 109/775] gfx2hlsl: lower 2D depth-comparison image sampling (image_sample_c, image_sample_c_lz) The reference is the first address register. The sampler becomes a SamplerComparisonState listed as an smpc manifest line, and the runtime builds the matching comparison static sampler. image_sample_c_l is refused: SampleCmpLevel needs shader model 6.7. AI-assisted; commands listed were executed locally. --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 7 + docs/experiments.md | 15 + .../translated_sampler_bindings.h | 27 +- tests/startup_image_sample_c_check.py | 406 ++++++++++++++++++ tests/startup_sampler_comparison_check.cpp | 61 +++ tools/startup/gfx2hlsl.py | 73 +++- 7 files changed, 584 insertions(+), 7 deletions(-) create mode 100644 tests/startup_image_sample_c_check.py create mode 100644 tests/startup_sampler_comparison_check.cpp diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 0fac297b1..1dd661a64 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -50,6 +50,7 @@ jobs: python3 -B tests/ffx_dispatch_aot_check.py llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/startup_sampler_heap_check.py binary llvm-mc-15 python3 -B tests/startup_image_sample_l_check.py binary llvm-mc-15 + python3 -B tests/startup_image_sample_c_check.py binary llvm-mc-15 python3 -B tests/startup_image_3d_check.py binary llvm-mc-15 python3 -B tests/startup_image_load_mip_check.py --llvm-mc llvm-mc-15 python3 -B tests/startup_image_2d_array_check.py binary llvm-mc-15 @@ -110,6 +111,7 @@ jobs: python -B tests/rectlist_topology_check.py python -B tests/startup_sampler_heap_check.py python -B tests/startup_image_sample_l_check.py + python -B tests/startup_image_sample_c_check.py python -B tests/startup_image_3d_check.py python -B tests/startup_image_load_mip_check.py python -B tests/startup_image_2d_array_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ac9066e87..ece335582 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -669,6 +669,11 @@ foreach(mutation IN ITEMS stand-in array b565 view) add_test(NAME startup_packed_target_${mutation}_control COMMAND startup_packed_target_check --mutate ${mutation}) set_tests_properties(startup_packed_target_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# Static samplers built from smp and smpc manifest lines (src/startup_stubs/translated_sampler_bindings.h). +add_executable(startup_sampler_comparison_check tests/startup_sampler_comparison_check.cpp) +target_include_directories(startup_sampler_comparison_check PRIVATE src) +target_compile_features(startup_sampler_comparison_check PRIVATE cxx_std_17) +add_test(NAME startup_sampler_comparison COMMAND startup_sampler_comparison_check) # Diagnostic line for a refused device slot 70 call (src/startup_stubs/memory_srv_report.h). add_executable(startup_memory_srv_report_check tests/startup_memory_srv_report_check.cpp) target_include_directories(startup_memory_srv_report_check PRIVATE src) @@ -1407,6 +1412,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_uniform_lane_check.py") add_test(NAME startup_image_sample_l COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_l_check.py") + add_test(NAME startup_image_sample_c COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_c_check.py") # Rewrites for instructions the host processor lacks (tools/startup/host_cpu.py), run on the host. add_test(NAME startup_host_cpu COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_host_cpu_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 471a05c73..bdc09304f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9725,6 +9725,21 @@ measurement on hardware or in a Windows run backs the descriptions. `v_interp_p1 `tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array, cube and multisample dimensions, an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) +## Startup translator: depth-comparison image sampling + +`tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_c_lz` and `image_sample_c` forms of a 2D texture to `tex.SampleCmpLevelZero(smp, float2(u, v), reference)` and, in a pixel stage with a known execution mask and no branches, `tex.SampleCmp(...)` for `image_sample_c`. The first address register is the reference, then u and v: `v[0:2]` compares `v0` at `(v1, v2)`, and the NSA list `[v3, v0, v1]` compares `v3` at `(v0, v1)`. Only `dmask:0x1` is lowered, and the result is the one float the comparison returns. The sampler must be four constant words that `pixel_aot.comparison_sampler_state` accepts (CLAMP_LAST_TEXEL, point or bilinear XY filter with the matching TRUNC_COORD, no anisotropy or bias); the comparison function is word 0 bits 14:12. It is bound as a `SamplerComparisonState` and written to the manifest as `smpc N w0 w1 w2 w3` beside the existing `smp` lines, so a sampler used by an ordinary sample and by a comparison gets two bindings. `src/startup_stubs/translated_sampler_bindings.h` builds the matching D3D12 static sampler (comparison filter 0x80 or 0x94, function = hardware function + 1) and keeps manifest order as register order. + +`image_sample_c_l` is refused: HLSL has no `SampleCmpLevel` before shader model 6.7 and the stages compile as 5.1 and 6.0. Array, 3D, cube and 1D images, other `dmask` values, offset, bias, clamp and gather forms, the `a16`, `d16`, `tfe`, `lwe`, `r128` and `unorm` modifiers, reserved MIMG bits, a sampler read from a run-time heap, and a sampler outside the checked profile are refused with their own message. + +`tests/startup_image_sample_c_check.py` translates source-built fixtures (the words are checked against `llvm-mc`, LLVM 15 and 19) and requires the exact call, register order and sampler type. Seven edited lowerings must each fail that check: the reference read from the last register, the reference swapped with u, the NSA reference taken as the first listed register, `SamplerState` instead of `SamplerComparisonState`, `SampleCmp` for `SampleCmpLevelZero` and the reverse, and `SampleLevel` instead of a comparison; each keeps the registers the correct fixture reads. All eight comparison functions have their own `smpc` line. `tests/startup_sampler_comparison_check.cpp` checks, without a device, that `smpc` lines become comparison static samplers for all eight functions and both filters, that an `smp` line stays an ordinary sampler, and that the register follows manifest order; changing the function offset, the filter reduction or the `smpc` parsing each makes it fail. + +```powershell +cmake --build --preset dev --target startup_sampler_comparison_check +ctest --preset dev --no-tests=error -R '^(startup_image_sample_c|startup_sampler_comparison)$' -V +``` + +Not covered: a D3D12 readback of a translated comparison draw. The compared result for the same sampler words and the same HLSL call is read back on WARP by `tests/pixel_compare_check.py` for the pixel AOT path, but no draw runs the `gfx2hlsl.py` output with an `smpc` sampler yet; 2D array comparisons; explicit-level comparison (`image_sample_c_l`), which needs a provable constant level 0 or shader model 6.7. + ## Startup translator: per-lane bit operations `tools/startup/gfx2hlsl.py` now lowers six gfx1013 per-lane bit operations that it used to refuse: `v_bfe_i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32`, `v_ffbh_i32` and `v_bfrev_b32`. They become single HLSL expressions, so no helper function is added to the output: `countbits(a) + b`, `firstbitlow(a)`, `reversebits(a)`, and, for the two high scans, `a == 0u ? 0xffffffffu : 31u - firstbithigh(a)` (the signed form scans `~a` for a negative value and reads 0xffffffff for 0 and -1). `v_bfe_i32` takes the offset from bits 4:0 of source 1 and the width from bits 4:0 of source 2, reads 0 for a width of 0, and sign-extends the field from its top bit; when offset plus width passes 32, the bits above bit 31 repeat bit 31, which is an arithmetic shift of the whole word. The formulas and edge cases are the ones `tools/pixel_aot.py` already draws on WARP. `v_bfe_i32` and `v_bcnt_u32_b32` exist only as VOP3 on gfx1013 (llvm-mc 19 rejects `_e32`); the other four assemble in both `_e32` and `_e64`. Source modifiers, `clamp`, output modifiers, `op_sel` and a wrong operand count are refused with `Unsupported`; the operand count is now checked for every integer operation in this table, where a missing operand used to raise `IndexError`. Not lowered here: the 64-bit carry forms, `v_bfm_b32`, the 24-bit multiplies and `v_alignbit_b32`. diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 012246a7c..1375b4562 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -19,7 +19,9 @@ constexpr UINT translated_sampler_space = 1; constexpr UINT translated_sampler_fallback = translated_sampler_count - 1; constexpr UINT title_sampler_stride = sizeof(SamplerWords); -inline D3D12_STATIC_SAMPLER_DESC decode_sampler(const SamplerWords& words, UINT shader_register) +// comparison: the sampler is read through a SamplerComparisonState (manifest line smpc). SQ_IMG_SAMP_WORD0 bits +// 14:12 hold SQ_TEX_DEPTH_COMPARE, which lists NEVER..ALWAYS in the order of D3D12_COMPARISON_FUNC minus one. +inline D3D12_STATIC_SAMPLER_DESC decode_sampler(const SamplerWords& words, UINT shader_register, bool comparison = false) { static const D3D12_TEXTURE_ADDRESS_MODE modes[8] = { D3D12_TEXTURE_ADDRESS_MODE_WRAP, D3D12_TEXTURE_ADDRESS_MODE_MIRROR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -35,6 +37,10 @@ inline D3D12_STATIC_SAMPLER_DESC decode_sampler(const SamplerWords& words, UINT s.MaxAnisotropy = 1u << ((words[0] >> 9) & 7); if (s.MaxAnisotropy > 16) s.MaxAnisotropy = 16; s.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; + if (comparison) { + s.Filter = D3D12_ENCODE_BASIC_FILTER(min & 1, mag & 1, mip == 2 ? 1 : 0, D3D12_FILTER_REDUCTION_TYPE_COMPARISON); + s.ComparisonFunc = static_cast(((words[0] >> 12) & 7) + 1); + } s.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; s.MaxLOD = D3D12_FLOAT32_MAX; s.ShaderRegister = shader_register; @@ -44,6 +50,7 @@ inline D3D12_STATIC_SAMPLER_DESC decode_sampler(const SamplerWords& words, UINT struct TranslatedSamplers { std::vector statics; + std::vector comparison; // parallel to statics: bound as SamplerComparisonState bool heap = false; bool reserved_fallback = false; @@ -64,13 +71,26 @@ struct TranslatedSamplers { } else { int index = 0; unsigned words[4] = {}; - if (std::sscanf(line, "smp %d %x %x %x %x", &index, &words[0], &words[1], &words[2], &words[3]) == 5) + const bool compare = std::strncmp(line, "smpc", 4) == 0; + if (std::sscanf(line, compare ? "smpc %d %x %x %x %x" : "smp %d %x %x %x %x", &index, &words[0], &words[1], + &words[2], &words[3]) == 5) { statics.push_back({words[0], words[1], words[2], words[3]}); + comparison.push_back(compare); + } } return true; } }; +// The static sampler bound at register i, in manifest order. +inline std::vector decode_statics(const TranslatedSamplers& samplers) +{ + std::vector statics; + for (UINT i = 0; i < samplers.statics.size(); ++i) + statics.push_back(decode_sampler(samplers.statics[i], i, i < samplers.comparison.size() && samplers.comparison[i])); + return statics; +} + inline UINT sampler_root_parameter(UINT srvs) { return srvs ? 2u : 1u; } inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, @@ -90,8 +110,7 @@ inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT parameters[count].DescriptorTable = {1, &sampler_range}; ++count; } - std::vector statics; - for (UINT i = 0; i < samplers.statics.size(); ++i) statics.push_back(decode_sampler(samplers.statics[i], i)); + const auto statics = decode_statics(samplers); const D3D12_ROOT_SIGNATURE_DESC desc{count, parameters, static_cast(statics.size()), statics.data(), D3D12_ROOT_SIGNATURE_FLAG_NONE}; ComPtr blob; diff --git a/tests/startup_image_sample_c_check.py b/tests/startup_image_sample_c_check.py new file mode 100644 index 000000000..7979fc884 --- /dev/null +++ b/tests/startup_image_sample_c_check.py @@ -0,0 +1,406 @@ +"""Depth-comparison sampling (image_sample_c, image_sample_c_lz) in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + binary reassemble every fixture source and compare it with the recorded words + +Each fixture is a source-built gfx1013 pixel stage that sets v0 = 0.5, v1 = 0.25, v2 = 1.0, v3 = 2.0, builds a +constant comparison sampler in s[24:27] (point filtering, clamp, one SQ_TEX_DEPTH_COMPARE function) and runs one +image instruction on a texture from descriptor table 0. The address dwords of a comparison are the reference, then +u and v, so the contiguous form v[0:2] compares v0 against the texel at (v1, v2) and the NSA form [v3, v0, v1] +compares v3 at (v0, v1): the lowering must follow the position, not the register number. The sampler is declared +as a SamplerComparisonState and listed as an smpc manifest line, even where its words equal an ordinary sampler's. + +HLSL has no SampleCmpLevel before shader model 6.7, so image_sample_c_l is refused, as are the forms and +modifiers the lowering does not read. The comparison results themselves are checked on D3D12 for the same sampler +words by tests/pixel_compare_check.py; startup_sampler_comparison_check.cpp checks what the runtime binds for an smpc line. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, assemble, root_blob # noqa: E402 + +PRE = """\ +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, {w0:#x} +s_mov_b32 s25, 0 +s_mov_b32 s26, {w2:#x} +s_mov_b32 s27, 0 +v_mov_b32 v0, 0.5 +v_mov_b32 v1, 0x3e800000 +v_mov_b32 v2, 1.0 +v_mov_b32 v3, 2.0 +s_waitcnt lgkmcnt(0) +""" +POST = """\ +s_waitcnt vmcnt(0) +exp mrt0 v4, v4, v4, v4 done vm +s_endpgm +""" +# SQ_IMG_SAMP_WORD0: CLAMP_LAST_TEXEL (2) in X and Y, the comparison function in bits 14:12, and TRUNC_COORD in +# bit 27 for point filtering. Word 2 bits 20..23 are the magnification and minification filters. +POINT = 2 | 2 << 3 | 1 << 27 +LESS = 1 << 12 +BILINEAR_W2 = 1 << 20 | 1 << 22 +IMAGE = { + 'lz': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'lz_nsa': 'image_sample_c_lz v4, [v3, v0, v1], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'c': 'image_sample_c v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'c_nsa': 'image_sample_c v4, [v3, v0, v1], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'c_l': 'image_sample_c_l v4, v[0:3], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'c_l_nsa': 'image_sample_c_l v4, [v3, v0, v1, v2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'glc': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D glc', + 'slc': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D slc', + 'dlc': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D dlc', + 'dmask3': 'image_sample_c_lz v[4:6], v[0:2], s[16:23], s[24:27] dmask:0x7 dim:SQ_RSRC_IMG_2D', + 'dmask2': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x2 dim:SQ_RSRC_IMG_2D', + 'array': 'image_sample_c_lz v4, v[0:3], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY', + 'three': 'image_sample_c_lz v4, v[0:3], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_3D', + 'cube': 'image_sample_c_lz v4, v[0:3], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_CUBE', + 'dim1d': 'image_sample_c_lz v4, v[0:1], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_1D', + 'offset': 'image_sample_c_lz_o v4, v[0:3], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'bias': 'image_sample_c_b v4, v[0:3], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'clamp': 'image_sample_c_cl v4, v[0:3], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'gather': 'image_gather4_c_lz v[4:7], v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'a16': 'image_sample_c_lz v4, v[0:1], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D a16', + 'tfe': 'image_sample_c_lz v[4:5], v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D tfe', + 'unorm': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm', + 'lwe': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D lwe', + 'd16': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D d16', + 'r128': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D r128', +} +# name -> (image key, sampler word 0, sampler word 2) +VARIANTS = {name: (name, POINT | LESS, 0) for name in IMAGE} +VARIANTS.update({'func%d' % n: ('lz', POINT | n << 12, 0) for n in range(8) if n != 1}) +VARIANTS['bilinear'] = ('lz', 2 | 2 << 3 | LESS, BILINEAR_W2) +VARIANTS['zero_sampler'] = ('lz', 0, 0) +VARIANTS['point_no_trunc'] = ('lz', 2 | 2 << 3 | LESS, 0) +VARIANTS['anisotropic'] = ('lz', POINT | LESS | 1 << 9, 0) +VARIANTS['wrap_x'] = ('lz', (POINT | LESS) & ~7, 0) +VARIANTS['mixed'] = ('mixed', POINT | LESS, 0) +WORDS = { + 'lz': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'lz_nsa': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0a01bcf00304c40000010000' + '703f8cbf0f1800f804040404000081bf'), + 'c': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801a0f00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'c_nsa': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0a01a0f00304c40000010000' + '703f8cbf0f1800f804040404000081bf'), + 'c_l': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801b0f00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'c_l_nsa': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0a01b0f00304c40000010200' + '703f8cbf0f1800f804040404000081bf'), + 'glc': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0821bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'slc': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf20004c400703f8cbf' + '0f1800f804040404000081bf'), + 'dlc': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf8801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'dmask3': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0807bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'dmask2': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0802bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'array': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf2801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'three': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf1001bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'cube': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf1801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'dim1d': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0001bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'offset': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801fcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'bias': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801b4f00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'clamp': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801a4f00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'gather': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf08013cf10004c400703f8cbf' + '0f1800f804040404000081bf'), + 'a16': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c440703f8cbf' + '0f1800f804040404000081bf'), + 'tfe': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bdf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'unorm': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0811bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'lwe': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bef00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'd16': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c480703f8cbf' + '0f1800f804040404000081bf'), + 'r128': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0881bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'func0': bytes.fromhex( + '04040cf4000000faff0398be12000008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'func2': bytes.fromhex( + '04040cf4000000faff0398be12200008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'func3': bytes.fromhex( + '04040cf4000000faff0398be12300008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'func4': bytes.fromhex( + '04040cf4000000faff0398be12400008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'func5': bytes.fromhex( + '04040cf4000000faff0398be12500008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'func6': bytes.fromhex( + '04040cf4000000faff0398be12600008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'func7': bytes.fromhex( + '04040cf4000000faff0398be12700008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'bilinear': bytes.fromhex( + '04040cf4000000faff0398be12100000800399beff039abe0000500080039bbe' + 'f002007eff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400' + '703f8cbf0f1800f804040404000081bf'), + 'zero_sampler': bytes.fromhex( + '04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e' + '0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf0f1800f8' + '04040404000081bf'), + 'point_no_trunc': bytes.fromhex( + '04040cf4000000faff0398be12100000800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'anisotropic': bytes.fromhex( + '04040cf4000000faff0398be12120008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'wrap_x': bytes.fromhex( + '04040cf4000000faff0398be10100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801bcf00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'mixed': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf08019cf00005c4000801bcf0' + '0004c400703f8cbf0f1800f804040404000081bf'), +} + + +def source(name): + key, w0, w2 = VARIANTS[name] + if key == 'mixed': + # One sampler used by an ordinary and a comparison sample: two bindings, never one SamplerState. + body = ('image_sample_lz v5, v[0:1], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D\n' + + IMAGE['lz'] + '\n') + else: + body = IMAGE[key] + '\n' + return PRE.format(w0=w0, w2=w2) + body + POST + + +# Reserved gfx10 MIMG bits: llvm-mc cannot assemble them, so each fixture sets one in the plain instruction. +RESERVED = {'reserved_w0_6': (1 << 6, 0), 'reserved_w0_14': (1 << 14, 0)} +RESERVED.update({'reserved_w1_%d' % bit: (0, 1 << bit) for bit in range(26, 30)}) +PLAIN_INSTRUCTION = bytes.fromhex('0801bcf00004c400') + + +def reserved_words(name): + w0, w1 = struct.unpack(' r0' in lz.hlsl_ps() and 'srv 0 tex2d table 0 0' in lz.manifest() + assert manifest_samplers(lz) == ['smpc 0 0x%x 0x0 0x0 0x0' % (POINT | LESS)], manifest_samplers(lz) + print('lz: reference v0 at (v1, v2); NSA reference v3 at (v0, v1); c uses SampleCmp; sampler smpc') + + # The comparison function travels in word 0 bits 14:12, one function per fixture. + for n in range(8): + name = 'lz' if n == 1 else 'func%d' % n + assert manifest_samplers(pipeline(name)) == ['smpc 0 0x%x 0x0 0x0 0x0' % (POINT | n << 12)], name + check_call(pipeline(name).hlsl_ps(), 'SampleCmpLevelZero', 'v1', 'v2', 'v0') + assert manifest_samplers(pipeline('bilinear')) == ['smpc 0 0x%x 0x0 0x%x 0x0' % (2 | 2 << 3 | LESS, BILINEAR_W2)] + print('all eight comparison functions and the bilinear filter reach the manifest') + + # The same words used by image_sample_lz and image_sample_c_lz are two bindings of different types. + mixed = pipeline('mixed') + text = mixed.hlsl_ps() + assert 'SamplerState q0 : register(s0);' in text and 'SamplerComparisonState q1 : register(s1);' in text, text + assert 'SampleLevel(q0,' in text and 'SampleCmpLevelZero(q1,' in text, text + assert manifest_samplers(mixed) == ['smp 0 0x%x 0x0 0x0 0x0' % (POINT | LESS), + 'smpc 1 0x%x 0x0 0x0 0x0' % (POINT | LESS)], manifest_samplers(mixed) + print('one sampler used both ways: smp 0 as SamplerState, smpc 1 as SamplerComparisonState') + + # Cache-policy bits do not change the compared value. + for name in ('glc', 'slc', 'dlc'): + assert pipeline(name).hlsl_ps() == lz.hlsl_ps(), name + + refused('c_l', 'image_sample_c_l') # SampleCmpLevel is shader model 6.7 + refused('c_l_nsa', 'shader model 6.7') + refused('dmask3', 'dmask 0x7') + refused('dmask2', 'dmask 0x2') + for name, dim in (('array', '2D_ARRAY'), ('three', '3D'), ('cube', 'CUBE'), ('dim1d', '1D')): + refused(name, 'image_sample_c_lz on SQ_RSRC_IMG_' + dim) + refused('offset', 'image_sample_c_lz_o') + refused('bias', 'image_sample_c_b') + refused('clamp', 'image_sample_c_cl') + refused('gather', 'image_gather4_c_lz') + for name in ('a16', 'tfe', 'unorm', 'lwe', 'd16', 'r128'): + refused(name, 'image_sample_c_lz modifier %s' % name) + for name in RESERVED: + refused(name, 'image_sample_c_lz modifier reserved') + refused('zero_sampler', 'sampler: Comparison sampling requires CLAMP_LAST_TEXEL') + refused('wrap_x', 'sampler: Comparison sampling requires CLAMP_LAST_TEXEL') + refused('anisotropic', 'sampler: Comparison sampling with anisotropy') + refused('point_no_trunc', 'sampler: Comparison sampling with point filtering requires TRUNC_COORD 1') + print('refused: c_l, extra dmask channels, array/3D/cube/1D, offset/bias/clamp/gather, ' + 'a16/tfe/unorm/lwe/d16/r128, reserved bits, samplers outside the checked profile') + + +def negative_controls(): + """Wrong lowerings, made by editing the correct text, must fail the exact checks above. + + Every mutant keeps the registers the correct fixture reads, so only the edited call differs. + """ + good = pipeline('lz').hlsl_ps() + nsa = pipeline('lz_nsa').hlsl_ps() + implicit = pipeline('c').hlsl_ps() + exact = ('SampleCmpLevelZero', 'v1', 'v2', 'v0') + mutants = ( + ('reference read from the last address register', good.replace('F(v2)), F(v0))', 'F(v1)), F(v2))'), exact), + ('reference swapped with u', good.replace('float2(F(v1), F(v2)), F(v0)', 'float2(F(v0), F(v2)), F(v1)'), exact), + ('NSA reference taken as the first listed register', nsa.replace('F(v3))', 'F(v1))'), + ('SampleCmpLevelZero', 'v0', 'v1', 'v3')), + ('ordinary SamplerState instead of SamplerComparisonState', + good.replace('SamplerComparisonState', 'SamplerState'), exact), + ('SampleCmp instead of SampleCmpLevelZero', good.replace('SampleCmpLevelZero', 'SampleCmp'), exact), + ('SampleCmpLevelZero instead of SampleCmp', implicit.replace('SampleCmp(', 'SampleCmpLevelZero('), + ('SampleCmp', 'v1', 'v2', 'v0')), + ('SampleLevel instead of a comparison', + good.replace('SampleCmpLevelZero(q0, float2(F(v1), F(v2)), F(v0))', 'SampleLevel(q0, float2(F(v1), F(v2)), 0).x'), + exact), + ) + for label, text, want in mutants: + try: + check_call(text, *want) + except AssertionError: + print('mutant fails the exact call check:', label) + else: + raise AssertionError('mutant passed: ' + label) + # A wrong comparison function is a different manifest word: each function has its own smpc line. + lines = [manifest_samplers(pipeline('lz' if n == 1 else 'func%d' % n)) for n in range(8)] + assert all(lines[n] != lines[m] for n in range(8) for m in range(8) if n != m), lines + print('each of the eight comparison functions has its own smpc line') + + +def check_binary(llvm_mc): + for name in WORDS: + built = assemble(llvm_mc, source(name)) + if built != WORDS[name]: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), WORDS[name].hex())) + print('fixture words match llvm-mc') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + negative_controls() + elif sys.argv[1] == 'binary' and len(sys.argv) == 3: + check_binary(sys.argv[2]) + else: + sys.exit(__doc__) diff --git a/tests/startup_sampler_comparison_check.cpp b/tests/startup_sampler_comparison_check.cpp new file mode 100644 index 000000000..1f14a9619 --- /dev/null +++ b/tests/startup_sampler_comparison_check.cpp @@ -0,0 +1,61 @@ +// Checks the static samplers src/startup_stubs/translated_sampler_bindings.h builds from manifest lines, +// without a device: a smpc line is a comparison sampler (D3D12 comparison filter and function from the +// SQ_IMG_SAMP words), a smp line stays an ordinary one, and the manifest order is the register order. +#include "startup_stubs/translated_sampler_bindings.h" + +#include + +namespace { +int failures; + +void expect(bool ok, const char* what, int a = 0, int b = 0) +{ + if (!ok) { + std::printf("FAIL %s (%d, %d)\n", what, a, b); + ++failures; + } +} + +// SQ_TEX_DEPTH_COMPARE 0..7 in hardware order, written as the D3D12 enumerators. +const D3D12_COMPARISON_FUNC funcs[8] = { + D3D12_COMPARISON_FUNC_NEVER, D3D12_COMPARISON_FUNC_LESS, D3D12_COMPARISON_FUNC_EQUAL, + D3D12_COMPARISON_FUNC_LESS_EQUAL, D3D12_COMPARISON_FUNC_GREATER, D3D12_COMPARISON_FUNC_NOT_EQUAL, + D3D12_COMPARISON_FUNC_GREATER_EQUAL, D3D12_COMPARISON_FUNC_ALWAYS}; +} // namespace + +int main() +{ + for (unsigned func = 0; func < 8; ++func) + for (unsigned linear = 0; linear < 2; ++linear) { + // CLAMP_LAST_TEXEL in X and Y, TRUNC_COORD with point filtering, the XY filter in word 2 bits 20..23. + const unsigned w0 = 2u | 2u << 3 | func << 12 | (linear ? 0u : 1u << 27); + const unsigned w2 = linear ? 1u << 20 | 1u << 22 : 0u; + char line[96]; + std::snprintf(line, sizeof(line), "smpc 0 0x%x 0x0 0x%x 0x0", w0, w2); + x2w_startup::TranslatedSamplers samplers; + expect(samplers.read_manifest_line(line) && samplers.statics.size() == 1, "smpc line parsed", func, linear); + const auto decoded = x2w_startup::decode_statics(samplers); + if (decoded.size() != 1) continue; + const auto& s = decoded[0]; + // D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT is 0x80, ..._MIN_MAG_LINEAR_MIP_POINT is 0x94. + expect(s.Filter == (linear ? 0x94 : 0x80), "comparison filter", func, linear); + expect(s.ComparisonFunc == funcs[func], "comparison function", func, linear); + expect(s.AddressU == D3D12_TEXTURE_ADDRESS_MODE_CLAMP && s.AddressV == D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + "clamp addressing", func, linear); + } + + // An ordinary smp line is not a comparison sampler, whatever bits 14:12 hold, and keeps its register. + x2w_startup::TranslatedSamplers mixed; + expect(mixed.read_manifest_line("smp 0 0x7012 0x0 0x0 0x0") && + mixed.read_manifest_line("smpc 1 0x1012 0x0 0x0 0x0"), "mixed lines parsed"); + const auto both = x2w_startup::decode_statics(mixed); + expect(both.size() == 2, "two samplers", int(both.size())); + if (both.size() == 2) { + expect(both[0].ShaderRegister == 0 && both[0].Filter == 0x0 && both[0].ComparisonFunc == D3D12_COMPARISON_FUNC_ALWAYS, + "ordinary sampler at register 0", both[0].Filter, both[0].ComparisonFunc); + expect(both[1].ShaderRegister == 1 && both[1].Filter == 0x80 && both[1].ComparisonFunc == D3D12_COMPARISON_FUNC_LESS, + "comparison sampler at register 1", both[1].Filter, both[1].ComparisonFunc); + } + std::printf(failures ? "startup_sampler_comparison failed\n" : "startup_sampler_comparison ok\n"); + return failures ? 1 : 0; +} diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3c2a4a534..c46ea5961 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -742,6 +742,70 @@ def image(self, ops, mods, how): self.set_v(n, 'U(t.%s)' % comp) n += 1 + def image_compare(self, ops, mods, how): + """image_sample_c and image_sample_c_lz: a 2D depth comparison returning one float. + + The address dwords are the reference, then u and v, which is what SampleCmp* takes as its third + argument and its location. The comparison function and the filter live in the sampler descriptor, + so they are read from its constant words by the decoder the pixel AOT path already checks against + D3D12 (pixel_aot.comparison_sampler_state) and bound as a SamplerComparisonState. HLSL has no + SampleCmpLevel before shader model 6.7 (the stages here compile as 5.1 and 6.0), so + image_sample_c_l is refused instead of being sampled at level zero. + """ + base = 'image_sample_' + how + if how == 'c_l': + raise Unsupported('image_sample_c_l: SampleCmpLevel needs shader model 6.7; only c and c_lz are lowered') + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + raise Unsupported('%s modifier %s' % (base, m)) + dims = [m[4:] for m in mods if m.startswith('dim:')] + masks = [m[6:] for m in mods if m.startswith('dmask:')] + if len(dims) != 1 or len(masks) != 1: + raise Unsupported('%s without exactly one dim and dmask' % base) + dim, dmask = dims[0], int(masks[0], 0) + if dim != 'SQ_RSRC_IMG_2D': + raise Unsupported('%s on %s' % (base, dim)) + if dmask != 1: + raise Unsupported('%s with dmask %#x: a comparison returns one channel' % (base, dmask)) + if len(ops) != 4: + raise Unsupported('%s with %d operands' % (base, len(ops))) + coords = ops[1] + if coords.startswith('['): + cs = [c.strip() for c in coords[1:-1].split(',')] + else: + r = reg_range(coords) + cs = ['v%d' % n for n in range(r[1], r[2] + 1)] + if len(cs) != 3: + raise Unsupported('%s with %d address registers' % (base, len(cs))) + if self.heap_sampler(ops[3]): + raise Unsupported('%s through a sampler heap' % base) + words = self.const_words(ops[3]) + if words is None: + raise Unsupported('%s with a sampler that is not constant' % base) + import pixel_aot + try: + pixel_aot.comparison_sampler_state(tuple(words)) + except ValueError as error: + raise Unsupported('%s sampler: %s' % (base, error)) + tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2d') + smp = self.pipe.sampler(tuple(words), comparison=True) + args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[1]), self.f(cs[2]), self.f(cs[0])) + # Implicit derivatives exist only in a pixel stage, as for image_sample. + if how == 'c' and self.exec_known and self.kind == 'ps' and len(self.blocks) == 0: + call = '%s.SampleCmp(%s)' % (tex, args) + else: + call = '%s.SampleCmpLevelZero(%s)' % (tex, args) + self.set_v(reg_range(ops[0])[1], 'U(%s)' % call) + + def op_image_sample_c(self, ops, mods): + self.image_compare(ops, mods, 'c') + + def op_image_sample_c_lz(self, ops, mods): + self.image_compare(ops, mods, 'c_lz') + + def op_image_sample_c_l(self, ops, mods): + self.image_compare(ops, mods, 'c_l') + def op_image_sample(self, ops, mods): self.image(ops, mods, 'sample') @@ -1102,9 +1166,11 @@ def resource(self, key, kind): raise Unsupported('resource %s used as %s and %s' % (key, r['kind'], kind)) return 'r%d' % r['index'] - def sampler(self, key): + def sampler(self, key, comparison=False): if not isinstance(key[0], int): raise Unsupported('sampler from a descriptor') + # A comparison sampler is its own binding even when its words equal an ordinary sampler's. + key = ('cmp',) + tuple(key) if comparison else key return 'q%d' % self.samplers.setdefault(key, len(self.samplers)) def common(self): @@ -1117,7 +1183,7 @@ def common(self): for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) for key, i in self.samplers.items(): - out.append('SamplerState q%d : register(s%d);' % (i, i)) + out.append('%s q%d : register(s%d);' % ('SamplerComparisonState' if key[0] == 'cmp' else 'SamplerState', i, i)) if self.uses_sampler_heap: out.append('SamplerState qh[%d] : register(s0, space%d);' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE)) out.append('uint x2w_sampler_entry(uint offset) { return (offset & 15u) != 0 || offset >= %du ? %du : offset >> 4; }' @@ -1182,7 +1248,8 @@ def manifest(self): raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) for key, i in self.samplers.items(): - lines.append('smp %d %s' % (i, ' '.join('0x%x' % w for w in key))) + comparison = key[0] == 'cmp' + lines.append('%s %d %s' % ('smpc' if comparison else 'smp', i, ' '.join('0x%x' % w for w in key[comparison:]))) if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) lines.append('params %d' % (max(self.params) + 1 if self.params else 0)) From 53497d1065582a707712dc180cfdbd0a7b61cd0b Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:36:08 +0100 Subject: [PATCH 110/775] startup_stubs/xapu: track handles and retire permissive command completions --- CMakeLists.txt | 6 ++ docs/startup-runtime.md | 8 ++ src/startup_stubs/xapu.cpp | 127 +++++++++++++++++----- tests/startup_xapu_queue_check.cpp | 167 +++++++++++++++++++++++++++++ 4 files changed, 283 insertions(+), 25 deletions(-) create mode 100644 tests/startup_xapu_queue_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ac9066e87..fa437b6eb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -347,6 +347,12 @@ add_dependencies(startup_acphal_apu_free startup_stub_acphal) add_test(NAME startup_acphal_apu_free COMMAND startup_acphal_apu_free "$") set_tests_properties(startup_acphal_apu_free PROPERTIES TIMEOUT 60) +add_executable(startup_xapu_queue_check tests/startup_xapu_queue_check.cpp) +target_compile_features(startup_xapu_queue_check PRIVATE cxx_std_17) +add_dependencies(startup_xapu_queue_check startup_stub_xapu) +add_test(NAME startup_xapu_queue COMMAND startup_xapu_queue_check "$") +set_tests_properties(startup_xapu_queue PROPERTIES TIMEOUT 60) + add_executable(startup_draw_bmp_check tests/startup_draw_bmp.cpp) add_test(NAME startup_draw_bmp COMMAND startup_draw_bmp_check) # Game-save stand-in storage (src/startup_stubs/save_store.h): a blob written by one process is read by a second. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0ece6dc15..c33c67a01 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -498,6 +498,14 @@ timer resolution for the mix worker's short refill waits. The last disconnect releases the request. This affects scheduling and preserves the existing audio routing and sample format. +With `X2W_AUDIO_PERMISSIVE=1`, `xapu.dll` tracks active handles across `XApuConnect` +and `XApuDisconnect`, refuses null outputs (`E_POINTER`) and unknown or disconnected +handles (`E_HANDLE`), and queues one completion entry per `XApuEnqueueCommand` call so +`XApuGetResultCount` and `XApuDequeueResult` retire commands cleanly (zeroing the +`0x58`-byte result buffer without fabricating unmeasured fields, and returning `E_FAIL` +when the queue is empty). Default non-permissive mode still traps on every export +(`ctest --preset dev --no-tests=error -R '^startup_xapu_queue$' -V`). + `src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only), converts each submitted block (format, frame count, bytes) to it, and writes it through diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index f357ae27b..b2fe3b9cd 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -5,6 +5,9 @@ #include "startup_stubs/trap.h" #include "startup_stubs/local_log.h" #include +#include +#include +#include // Experimental (docs/startup-runtime.md). With X2W_AUDIO_PERMISSIVE=1 the exports // stand in for the audio command queue; otherwise they trap. Call shapes from the title: @@ -14,15 +17,43 @@ // +0 (1..5 seen in its switch), a slot index at +4 and a value at +0x34 // XApuEnqueueCommand(handle, command*, ...) -> HRESULT // XApuDisconnect(handle) -// Nothing is processed: commands are accepted and logged, and no result is ever produced. +// Under X2W_AUDIO_PERMISSIVE=1 each active connection tracks its pending completion count so +// enqueued commands can be retired cleanly without fabricating unmeasured result fields. namespace { using u64 = std::uint64_t; +constexpr long hr_ok = 0; +constexpr long hr_pointer = static_cast(0x80004003); // E_POINTER +constexpr long hr_fail = static_cast(0x80004005); // E_FAIL +constexpr long hr_handle = static_cast(0x80070006); // E_HANDLE +constexpr std::size_t result_size = 0x58; + bool permissive() noexcept { return x2w_local::env_on("X2W_AUDIO_PERMISSIVE"); } -int connection; // its address is the handle + +struct Connection { + u64 handle = 0; + std::uint64_t pending_results = 0; +}; + SRWLOCK connection_lock = SRWLOCK_INIT; +u64 next_handle = 0x5841500000000001ULL; unsigned long long connection_count = 0; bool timer_active = false; +std::vector& connections() +{ + static auto* list = new std::vector(); + return *list; +} + +Connection* find_connection(u64 handle) noexcept +{ + if (!handle) return nullptr; + for (auto& conn : connections()) { + if (conn.handle == handle) return &conn; + } + return nullptr; +} + void hex(const void* data, std::size_t bytes, char* out, std::size_t size) { out[0] = 0; @@ -40,67 +71,113 @@ extern "C" __declspec(noinline) long XApuConnect(u64 rcx, u64 rdx, u64 r8, u64 r char input[3 * 0x18 + 1], output[3 * 0x10 + 1]; hex(reinterpret_cast(rcx), 0x18, input, sizeof(input)); hex(reinterpret_cast(rdx), 0x10, output, sizeof(output)); - if (r8) { - *reinterpret_cast(r8) = &connection; - AcquireSRWLockExclusive(&connection_lock); - if (connection_count++ == 0) { - // The mix worker sleeps for 2 ms between refills. A coarse Windows tick can - // stretch that wait beyond the time represented by the queued samples. - timer_active = timeBeginPeriod(1) == TIMERR_NOERROR; - if (!timer_active) x2w_local::logf("x2w-audio 1 ms mixer timer request unavailable"); - } - ReleaseSRWLockExclusive(&connection_lock); + if (!r8 || !x2w_local::writable(reinterpret_cast(r8), sizeof(void*))) { + x2w_local::logf("x2w-audio XApuConnect input=[%s] output(before)=[%s] -> E_POINTER", input, output); + return hr_pointer; + } + AcquireSRWLockExclusive(&connection_lock); + const u64 handle = next_handle++; + if (next_handle == 0) next_handle = 0x5841500000000001ULL; + connections().push_back({handle, 0}); + if (connection_count++ == 0) { + // The mix worker sleeps for 2 ms between refills. A coarse Windows tick can + // stretch that wait beyond the time represented by the queued samples. + timer_active = timeBeginPeriod(1) == TIMERR_NOERROR; + if (!timer_active) x2w_local::logf("x2w-audio 1 ms mixer timer request unavailable"); } + ReleaseSRWLockExclusive(&connection_lock); + *reinterpret_cast(r8) = reinterpret_cast(handle); x2w_local::logf("x2w-audio XApuConnect input=[%s] output(before)=[%s] -> handle %p, S_OK", input, output, - static_cast(&connection)); - return r8 ? 0 : static_cast(0x80004003); + reinterpret_cast(handle)); + return hr_ok; } extern "C" __declspec(noinline) std::uint32_t XApuGetResultCount(u64 rcx, u64 rdx, u64 r8, u64 r9) { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuGetResultCount", 4, rcx, rdx, r8, r9, _ReturnAddress()); + AcquireSRWLockShared(&connection_lock); + const Connection* conn = find_connection(rcx); + const std::uint32_t count = conn + ? static_cast(conn->pending_results > 0xFFFFFFFFULL ? 0xFFFFFFFFULL : conn->pending_results) + : 0u; + ReleaseSRWLockShared(&connection_lock); static LONG calls; - if (x2w_local::first_calls(calls, 2)) x2w_local::logf("x2w-audio XApuGetResultCount handle=0x%llx rdx=0x%llx -> 0", rcx, rdx); - return 0; + if (x2w_local::first_calls(calls, 2)) + x2w_local::logf("x2w-audio XApuGetResultCount handle=0x%llx rdx=0x%llx -> %u", rcx, rdx, count); + return count; } extern "C" __declspec(noinline) long XApuDequeueResult(u64 rcx, u64 rdx, u64 r8, u64 r9) { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuDequeueResult", 1, rcx, rdx, r8, r9, _ReturnAddress()); + if (!rdx || !x2w_local::writable(reinterpret_cast(rdx), result_size)) { + static LONG bad_out_calls; + if (x2w_local::first_calls(bad_out_calls, 2)) + x2w_local::logf("x2w-audio XApuDequeueResult handle=0x%llx -> E_POINTER", rcx); + return hr_pointer; + } + AcquireSRWLockExclusive(&connection_lock); + Connection* conn = find_connection(rcx); + long hr = hr_handle; + if (conn) { + if (conn->pending_results > 0) { + --conn->pending_results; + hr = hr_ok; + } else { + hr = hr_fail; + } + } + ReleaseSRWLockExclusive(&connection_lock); + if (hr == hr_ok) std::memset(reinterpret_cast(rdx), 0, result_size); static LONG calls; - if (x2w_local::first_calls(calls, 2)) x2w_local::logf("x2w-audio XApuDequeueResult handle=0x%llx -> E_FAIL (no results)", rcx); - return static_cast(0x80004005); + if (x2w_local::first_calls(calls, 2)) + x2w_local::logf("x2w-audio XApuDequeueResult handle=0x%llx -> 0x%08lx", rcx, static_cast(hr)); + return hr; } extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8, u64 r9) { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuEnqueueCommand", 3, rcx, rdx, r8, r9, _ReturnAddress()); + AcquireSRWLockExclusive(&connection_lock); + Connection* conn = find_connection(rcx); + long hr = hr_handle; + if (conn) { + ++conn->pending_results; + hr = hr_ok; + } + ReleaseSRWLockExclusive(&connection_lock); static LONG calls; if (x2w_local::first_calls(calls, 24)) { char command[3 * 0x60 + 1]; hex(reinterpret_cast(rdx), 0x60, command, sizeof(command)); const auto offset = reinterpret_cast(_ReturnAddress()) - reinterpret_cast(GetModuleHandleW(nullptr)); - x2w_local::logf("x2w-audio XApuEnqueueCommand r8=0x%llx r9=0x%llx ret=+0x%llx command=[%s] -> S_OK", r8, r9, offset, - command); + x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx r8=0x%llx r9=0x%llx ret=+0x%llx command=[%s] -> 0x%08lx", + rcx, r8, r9, offset, command, static_cast(hr)); } - return 0; + return hr; } extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u64 r9) { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuDisconnect", 2, rcx, rdx, r8, r9, _ReturnAddress()); - x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx", rcx); - if (rcx == reinterpret_cast(&connection)) { - AcquireSRWLockExclusive(&connection_lock); + AcquireSRWLockExclusive(&connection_lock); + auto& list = connections(); + auto it = std::find_if(list.begin(), list.end(), [rcx](const Connection& conn) { return conn.handle == rcx; }); + if (it != list.end()) { + list.erase(it); if (connection_count && --connection_count == 0 && timer_active) { timeEndPeriod(1); timer_active = false; } ReleaseSRWLockExclusive(&connection_lock); + x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> S_OK", rcx); + return hr_ok; } - return 0; + ReleaseSRWLockExclusive(&connection_lock); + x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> E_HANDLE", rcx); + return hr_handle; } diff --git a/tests/startup_xapu_queue_check.cpp b/tests/startup_xapu_queue_check.cpp new file mode 100644 index 000000000..203895f0b --- /dev/null +++ b/tests/startup_xapu_queue_check.cpp @@ -0,0 +1,167 @@ +// Lifecycle, queue retirement, and refusal checks for the xapu.dll startup stand-in. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include +#include +#include + +namespace { + +using ConnectFn = long(__cdecl*)(const void* input, void* output, void** handle); +using GetResultCountFn = std::uint32_t(__cdecl*)(void* handle, std::uint64_t unused); +using DequeueResultFn = long(__cdecl*)(void* handle, void* result); +using EnqueueCommandFn = long(__cdecl*)(void* handle, const void* command, std::uint64_t r8, std::uint64_t r9); +using DisconnectFn = long(__cdecl*)(void* handle); + +constexpr long hr_ok = 0; +constexpr long hr_pointer = static_cast(0x80004003); +constexpr long hr_fail = static_cast(0x80004005); +constexpr long hr_handle = static_cast(0x80070006); +constexpr DWORD trap_connect_exit = 0xE2570300u; +constexpr std::size_t result_bytes = 0x58; + +int failures = 0; + +void check(bool condition, const char* label) +{ + if (condition) return; + ++failures; + std::printf("FAIL: %s\n", label); +} + +bool all_zero(const std::array& bytes) +{ + for (unsigned char b : bytes) { + if (b != 0) return false; + } + return true; +} + +int run_trap_control(const char* dll_path) +{ + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", nullptr); + HMODULE module = LoadLibraryA(dll_path); + if (!module) return 2; + auto connect = reinterpret_cast(GetProcAddress(module, "XApuConnect")); + if (!connect) return 3; + std::array input{}; + std::array output{}; + void* handle = nullptr; + connect(input.data(), output.data(), &handle); + return 4; +} + +void check_non_permissive_trap(const char* self_exe, const char* dll_path) +{ + std::string cmd = std::string("\"") + self_exe + "\" --trap-control \"" + dll_path + "\""; + STARTUPINFOA si{}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + if (!CreateProcessA(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) { + check(false, "CreateProcessA for non-permissive trap control"); + return; + } + const DWORD wait_rc = WaitForSingleObject(pi.hProcess, 10000); + DWORD exit_code = 0; + const BOOL got_code = GetExitCodeProcess(pi.hProcess, &exit_code); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + check(wait_rc == WAIT_OBJECT_0, "non-permissive trap child exited within timeout"); + check(got_code && exit_code == trap_connect_exit, "non-permissive XApuConnect traps with 0xE2570300"); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && std::strcmp(argv[1], "--trap-control") == 0) return run_trap_control(argv[2]); + if (argc != 2) return std::printf("usage: startup_xapu_queue_check \n"), 2; + + check_non_permissive_trap(argv[0], argv[1]); + + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); + HMODULE module = LoadLibraryA(argv[1]); + if (!module) return std::printf("FAIL: cannot load %s\n", argv[1]), 2; + + auto connect = reinterpret_cast(GetProcAddress(module, "XApuConnect")); + auto get_count = reinterpret_cast(GetProcAddress(module, "XApuGetResultCount")); + auto dequeue = reinterpret_cast(GetProcAddress(module, "XApuDequeueResult")); + auto enqueue = reinterpret_cast(GetProcAddress(module, "XApuEnqueueCommand")); + auto disconnect = reinterpret_cast(GetProcAddress(module, "XApuDisconnect")); + if (!connect || !get_count || !dequeue || !enqueue || !disconnect) { + FreeLibrary(module); + return std::printf("FAIL: missing export\n"), 2; + } + + const std::array input{}; + std::array output{}; + const std::array cmd{}; + std::array result{}; + void* bogus = reinterpret_cast(static_cast(0xDEADBEEFULL)); + + // Invalid-handle and null-pointer negative controls before any connection exists. + check(connect(input.data(), output.data(), nullptr) == hr_pointer, "XApuConnect(null handle*) -> E_POINTER"); + check(get_count(nullptr, 0) == 0, "XApuGetResultCount(null) -> 0"); + check(get_count(bogus, 0) == 0, "XApuGetResultCount(bogus) -> 0"); + check(enqueue(nullptr, cmd.data(), 0, 0) == hr_handle, "XApuEnqueueCommand(null) -> E_HANDLE"); + check(enqueue(bogus, cmd.data(), 0, 0) == hr_handle, "XApuEnqueueCommand(bogus) -> E_HANDLE"); + check(dequeue(nullptr, result.data()) == hr_handle, "XApuDequeueResult(null handle) -> E_HANDLE"); + check(dequeue(bogus, result.data()) == hr_handle, "XApuDequeueResult(bogus handle) -> E_HANDLE"); + check(disconnect(nullptr) == hr_handle, "XApuDisconnect(null) -> E_HANDLE"); + check(disconnect(bogus) == hr_handle, "XApuDisconnect(bogus) -> E_HANDLE"); + + // Positive lifecycle: connect, enqueue, count, dequeue (zeroed 0x58 bytes), empty E_FAIL. + void* h1 = nullptr; + check(connect(input.data(), output.data(), &h1) == hr_ok && h1 != nullptr, "XApuConnect h1 succeeds"); + check(get_count(h1, 0) == 0, "initial XApuGetResultCount == 0"); + check(dequeue(h1, result.data()) == hr_fail, "empty queue XApuDequeueResult -> E_FAIL"); + + check(enqueue(h1, cmd.data(), 0x11, 0x22) == hr_ok, "enqueue #1 on h1"); + check(enqueue(h1, cmd.data(), 0x33, 0x44) == hr_ok, "enqueue #2 on h1"); + check(get_count(h1, 0) == 2, "XApuGetResultCount == 2 after 2 enqueues"); + + check(dequeue(h1, nullptr) == hr_pointer, "XApuDequeueResult(null result*) -> E_POINTER"); + check(get_count(h1, 0) == 2, "failed dequeue(null) does not consume queued entry"); + + result.fill(0xAA); + check(dequeue(h1, result.data()) == hr_ok, "dequeue #1 on h1 succeeds"); + check(all_zero(result), "dequeue #1 zeroes 0x58-byte result buffer"); + check(get_count(h1, 0) == 1, "XApuGetResultCount == 1 after first dequeue"); + + result.fill(0x55); + check(dequeue(h1, result.data()) == hr_ok, "dequeue #2 on h1 succeeds"); + check(all_zero(result), "dequeue #2 zeroes 0x58-byte result buffer"); + check(get_count(h1, 0) == 0, "XApuGetResultCount == 0 after draining queue"); + check(dequeue(h1, result.data()) == hr_fail, "drained queue XApuDequeueResult -> E_FAIL"); + + // Second independent handle + disconnect invalidation. + void* h2 = nullptr; + check(connect(input.data(), output.data(), &h2) == hr_ok && h2 != nullptr && h2 != h1, "XApuConnect h2 distinct"); + check(enqueue(h1, cmd.data(), 0, 0) == hr_ok, "enqueue on h1 before disconnect"); + check(enqueue(h2, cmd.data(), 0, 0) == hr_ok, "enqueue #1 on h2"); + check(enqueue(h2, cmd.data(), 0, 0) == hr_ok, "enqueue #2 on h2"); + + check(disconnect(h1) == hr_ok, "XApuDisconnect(h1) succeeds"); + check(disconnect(h1) == hr_handle, "repeat XApuDisconnect(h1) -> E_HANDLE"); + check(enqueue(h1, cmd.data(), 0, 0) == hr_handle, "enqueue after disconnect(h1) -> E_HANDLE"); + check(get_count(h1, 0) == 0, "get_count after disconnect(h1) -> 0"); + check(dequeue(h1, result.data()) == hr_handle, "dequeue after disconnect(h1) -> E_HANDLE"); + + check(get_count(h2, 0) == 2, "disconnect(h1) preserves h2 queue"); + check(dequeue(h2, result.data()) == hr_ok, "h2 dequeue #1 succeeds"); + check(dequeue(h2, result.data()) == hr_ok, "h2 dequeue #2 succeeds"); + check(dequeue(h2, result.data()) == hr_fail, "h2 drained -> E_FAIL"); + check(disconnect(h2) == hr_ok, "XApuDisconnect(h2) succeeds"); + + FreeLibrary(module); + std::printf(failures ? "startup_xapu_queue_check: %d failure(s)\n" : "startup_xapu_queue_check: ok\n", failures); + return failures ? 1 : 0; +} From d953dc6ad8d4cbea12e3d853b555778dc51fc4f2 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:36:30 +0100 Subject: [PATCH 111/775] tests: count only buffer-sized worker allocations in the all-thread allocation sweep --- tests/startup_storage_worker_start.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/startup_storage_worker_start.cpp b/tests/startup_storage_worker_start.cpp index 288343a08..c30518cab 100644 --- a/tests/startup_storage_worker_start.cpp +++ b/tests/startup_storage_worker_start.cpp @@ -74,7 +74,11 @@ void* operator new(std::size_t size) ++thrown; throw std::bad_alloc(); } - if (global_countdown.load(std::memory_order_relaxed) > 0 && global_countdown.fetch_sub(1) == 1) { + // On the queue's worker only buffer-sized allocations are counted: a small one there is the container + // proxy that MSVC's debug mode allocates inside a noexcept vector constructor, which has no recovery + // (std::terminate), while a failed buffer allocation fails the request. + const bool countable = size >= 4096 || GetCurrentThreadId() == main_thread_id; + if (countable && global_countdown.load(std::memory_order_relaxed) > 0 && global_countdown.fetch_sub(1) == 1) { ++thrown; throw std::bad_alloc(); } From 3b8588505a3e6c71f4bc42f5351d2fe6b26c8077 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 20:36:50 +0800 Subject: [PATCH 112/775] Use stream position for filtered previous GameInput reading --- src/startup_stubs/gameinput.cpp | 20 +++++++++++++++----- tests/startup_gameinput_keys.cpp | 8 +++++++- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/startup_stubs/gameinput.cpp b/src/startup_stubs/gameinput.cpp index b7294046f..b5031c9e7 100644 --- a/src/startup_stubs/gameinput.cpp +++ b/src/startup_stubs/gameinput.cpp @@ -278,6 +278,7 @@ struct Reading : Object { std::uint32_t key_count; KeyState keys[max_keys]; u64 timestamp; + u64 order; u64 pad_sequence, key_sequence; // per-kind sequence numbers, as GameInput documents them }; constexpr std::uint32_t history_pad = 1, history_keys = 2; @@ -416,14 +417,22 @@ std::uint32_t history_mask(std::uint32_t reading_kind) return (wants_gamepad(reading_kind) ? history_pad : 0) | ((reading_kind & kind_keyboard) ? history_keys : 0); } -// Looks `step` (+1 / -1) kinds-sequence away from `ref_sequence` in one kind's ring. +// Finds the nearest entry before or after the reference position in one kind's ring. // Returns 0 on hit, -1 if there is none (not found), -2 if the wanted entry was already evicted (too old). -int find_in_ring(const KindRing& ring, u64 ref_sequence, int step, HistoryEntry& out) +int find_in_ring(const KindRing& ring, u64 ref_sequence, u64 ref_order, int step, HistoryEntry& out) { if (ring.count == 0) return -1; - const u64 target = step > 0 ? ref_sequence + 1 : ref_sequence - 1; + const u64 oldest = ring.latest - ring.count + 1; + u64 target = ref_sequence + 1; + if (step < 0) { + if (ref_sequence == 0) return -1; + if (ref_sequence < oldest) return -2; + target = ref_sequence; + // A different kind may have advanced the stream since this kind last changed. + if (ring.entries[target % history_capacity].order == ref_order) --target; + } if (target == 0 || target > ring.latest) return -1; - if (target < ring.latest - ring.count + 1) return -2; + if (target < oldest) return -2; out = ring.entries[target % history_capacity]; return 0; } @@ -439,7 +448,7 @@ int find_history(const Reading& ref, int step, std::uint32_t mask, HistoryEntry& if (!(mask & bit)) continue; const KindRing& ring = i == 0 ? pad_ring : key_ring; HistoryEntry candidate{}; - const int found = find_in_ring(ring, i == 0 ? ref.pad_sequence : ref.key_sequence, step, candidate); + const int found = find_in_ring(ring, i == 0 ? ref.pad_sequence : ref.key_sequence, ref.order, step, candidate); if (found == -2) { result = -2; have = false; @@ -467,6 +476,7 @@ Reading* make_reading(const HistoryEntry& entry, std::uint32_t kind, Object* dev reading->pad_sequence = entry.pad_sequence; reading->key_sequence = entry.key_sequence; reading->timestamp = entry.timestamp; + reading->order = entry.order; return reading; } diff --git a/tests/startup_gameinput_keys.cpp b/tests/startup_gameinput_keys.cpp index 84ac1f741..b25ea7acf 100644 --- a/tests/startup_gameinput_keys.cpp +++ b/tests/startup_gameinput_keys.cpp @@ -385,7 +385,13 @@ int main(int argc, char** argv) IGameInputReading* kback = nullptr; failures += check(input->GetPreviousReading(pad_b, kind_keyboard, kbd_device, &kback) == S_OK && kback, "previous keyboard reading"); if (kback) { - failures += check(kback->GetSequenceNumber(kind_keyboard) == key52 - 1 && key52 > key51, "previous keyboard reading skips pad-only entries"); + failures += check(kback->GetSequenceNumber(kind_keyboard) == key52 && key52 > key51, + "previous keyboard reading skips pad-only entries"); + IGameInputReading* earlier_key = nullptr; + failures += check(input->GetPreviousReading(kback, kind_keyboard, kbd_device, &earlier_key) == S_OK && + earlier_key && earlier_key->GetSequenceNumber(kind_keyboard) == key52 - 1, + "previous keyboard reading steps back from a keyboard entry"); + if (earlier_key) earlier_key->Release(); kback->Release(); } pad_b->Release(); From 8ae3c180542f087f8fa86e6e2282988ae07704e4 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:37:01 +0100 Subject: [PATCH 113/775] gfx2hlsl: keep a sampler MAX_LOD limit on implicit depth comparisons --- tests/startup_image_sample_c_check.py | 34 ++++++++++++++++++++------- tools/startup/gfx2hlsl.py | 8 ++++++- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/tests/startup_image_sample_c_check.py b/tests/startup_image_sample_c_check.py index 7979fc884..324d4f5bb 100644 --- a/tests/startup_image_sample_c_check.py +++ b/tests/startup_image_sample_c_check.py @@ -28,7 +28,7 @@ PRE = """\ s_load_dwordx8 s[16:23], s[8:9], 0x0 s_mov_b32 s24, {w0:#x} -s_mov_b32 s25, 0 +s_mov_b32 s25, {w1:#x} s_mov_b32 s26, {w2:#x} s_mov_b32 s27, 0 v_mov_b32 v0, 0.5 @@ -74,6 +74,10 @@ 'd16': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D d16', 'r128': 'image_sample_c_lz v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D r128', } +# SQ_IMG_SAMP_WORD1 bits 23:12 are MAX_LOD (4.8 fixed point). The translated static sampler never limits the +# LOD, so an implicit-derivative comparison is lowered to SampleCmp only when the source does not limit it either. +MAX_LOD_FULL = 0xfff << 12 +W1 = {'c': MAX_LOD_FULL, 'c_nsa': MAX_LOD_FULL, 'c_max_partial': 1 << 12} # name -> (image key, sampler word 0, sampler word 2) VARIANTS = {name: (name, POINT | LESS, 0) for name in IMAGE} VARIANTS.update({'func%d' % n: ('lz', POINT | n << 12, 0) for n in range(8) if n != 1}) @@ -83,6 +87,8 @@ VARIANTS['anisotropic'] = ('lz', POINT | LESS | 1 << 9, 0) VARIANTS['wrap_x'] = ('lz', (POINT | LESS) & ~7, 0) VARIANTS['mixed'] = ('mixed', POINT | LESS, 0) +VARIANTS['c_max0'] = ('c', POINT | LESS, 0) +VARIANTS['c_max_partial'] = ('c', POINT | LESS, 0) WORDS = { 'lz': bytes.fromhex( '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' @@ -93,13 +99,13 @@ 'ff02027e0000803ef202047ef402067e7fc08cbf0a01bcf00304c40000010000' '703f8cbf0f1800f804040404000081bf'), 'c': bytes.fromhex( - '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' - 'ff02027e0000803ef202047ef402067e7fc08cbf0801a0f00004c400703f8cbf' - '0f1800f804040404000081bf'), - 'c_nsa': bytes.fromhex( - '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' - 'ff02027e0000803ef202047ef402067e7fc08cbf0a01a0f00304c40000010000' + '04040cf4000000faff0398be12100008ff0399be00f0ff0080039abe80039bbe' + 'f002007eff02027e0000803ef202047ef402067e7fc08cbf0801a0f00004c400' '703f8cbf0f1800f804040404000081bf'), + 'c_nsa': bytes.fromhex( + '04040cf4000000faff0398be12100008ff0399be00f0ff0080039abe80039bbe' + 'f002007eff02027e0000803ef202047ef402067e7fc08cbf0a01a0f00304c400' + '00010000703f8cbf0f1800f804040404000081bf'), 'c_l': bytes.fromhex( '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' 'ff02027e0000803ef202047ef402067e7fc08cbf0801b0f00004c400703f8cbf' @@ -236,6 +242,14 @@ '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' 'ff02027e0000803ef202047ef402067e7fc08cbf08019cf00005c4000801bcf0' '0004c400703f8cbf0f1800f804040404000081bf'), + 'c_max0': bytes.fromhex( + '04040cf4000000faff0398be12100008800399be80039abe80039bbef002007e' + 'ff02027e0000803ef202047ef402067e7fc08cbf0801a0f00004c400703f8cbf' + '0f1800f804040404000081bf'), + 'c_max_partial': bytes.fromhex( + '04040cf4000000faff0398be12100008ff0399be0010000080039abe80039bbe' + 'f002007eff02027e0000803ef202047ef402067e7fc08cbf0801a0f00004c400' + '703f8cbf0f1800f804040404000081bf'), } @@ -247,7 +261,7 @@ def source(name): + IMAGE['lz'] + '\n') else: body = IMAGE[key] + '\n' - return PRE.format(w0=w0, w2=w2) + body + POST + return PRE.format(w0=w0, w1=W1.get(name, 0), w2=w2) + body + POST # Reserved gfx10 MIMG bits: llvm-mc cannot assemble them, so each fixture sets one in the plain instruction. @@ -305,6 +319,10 @@ def controls(): check_call(pipeline('lz_nsa').hlsl_ps(), 'SampleCmpLevelZero', 'v0', 'v1', 'v3') # NSA: v3 is the reference check_call(pipeline('c').hlsl_ps(), 'SampleCmp', 'v1', 'v2', 'v0') # implicit derivatives in a pixel stage check_call(pipeline('c_nsa').hlsl_ps(), 'SampleCmp', 'v0', 'v1', 'v3') + # MAX_LOD 0 limits the source to level zero, so the implicit form is exactly SampleCmpLevelZero; a limit between + # 0 and the maximum has no static-sampler equivalent and is refused. + check_call(pipeline('c_max0').hlsl_ps(), 'SampleCmpLevelZero', 'v1', 'v2', 'v0') + refused('c_max_partial', 'sampler MAX_LOD') assert 'Texture2D r0' in lz.hlsl_ps() and 'srv 0 tex2d table 0 0' in lz.manifest() assert manifest_samplers(lz) == ['smpc 0 0x%x 0x0 0x0 0x0' % (POINT | LESS)], manifest_samplers(lz) print('lz: reference v0 at (v1, v2); NSA reference v3 at (v0, v1); c uses SampleCmp; sampler smpc') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index c46ea5961..b0134eb3a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -790,8 +790,14 @@ def image_compare(self, ops, mods, how): tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2d') smp = self.pipe.sampler(tuple(words), comparison=True) args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[1]), self.f(cs[2]), self.f(cs[0])) + # MAX_LOD (word 1 bits 23:12) is not carried into the static sampler, which never limits the LOD. Level + # zero is the exact lowering when the source limits it to 0; an implicit comparison cannot express any + # other limit below the maximum. + max_lod = (words[1] >> 12) & 0xfff + if how == 'c' and max_lod not in (0, 0xfff): + raise Unsupported('%s with a sampler MAX_LOD of %#x' % (base, max_lod)) # Implicit derivatives exist only in a pixel stage, as for image_sample. - if how == 'c' and self.exec_known and self.kind == 'ps' and len(self.blocks) == 0: + if how == 'c' and max_lod and self.exec_known and self.kind == 'ps' and len(self.blocks) == 0: call = '%s.SampleCmp(%s)' % (tex, args) else: call = '%s.SampleCmpLevelZero(%s)' % (tex, args) From d043bd913313a4db6493ed611eb88b7ba1fa4472 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 15:39:13 +0300 Subject: [PATCH 114/775] startup: check the translated sampler bindings src/startup_stubs/translated_sampler_bindings.h was reached only through the offscreen_check draws in startup_sampler_heap_warp and the image and inline sampler WARP tests. Those draws sample wrap, clamp and border samplers along U on one-texel-high or point-sampled textures and read one channel. Single-point mutants of the header (V or W read from the wrong bits, mirror and mirror-once swapped, min and mag filters swapped, a point mip filter read as linear, no 16x anisotropy cap, an opaque static border, a border sampler on U only, any fallback entry or a second smpheap line accepted, a snapshot that ignores the reserved entry, and a snapshot comparison that ignores the words or the readable bits) all left those six tests passing. No test sends an smpheap manifest through the device wrapper, where that comparison decides whether a draw reuses its sampler table. startup_translated_sampler_bindings includes the header without a device and checks hand-worked values: every clamp mode on each axis, anisotropy ratios 0 to 7, the filter fields, ignored bits, the border sampler, accepted and refused manifest lines, snapshot counts against the 2048 and 2047 entry limits, null and top-of-memory addresses, unaligned records across pages, records up to an inaccessible page, and snapshot equality field by field. Each of those mutants now fails it. The shared-axis control expects V and W to repeat U and must fail. --- CMakeLists.txt | 9 + docs/startup-runtime.md | 6 + ...rtup_translated_sampler_bindings_check.cpp | 291 ++++++++++++++++++ 3 files changed, 306 insertions(+) create mode 100644 tests/startup_translated_sampler_bindings_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 360629d97..90af36061 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -629,6 +629,15 @@ add_custom_command(OUTPUT "${startup_sampler_x_cs}" COMMAND "${DXC_EXECUTABLE}" DEPENDS tests/startup_sampler_x.hlsl VERBATIM) target_sources(offscreen_check PRIVATE tests/startup_sampler_x.cpp "${startup_sampler_x_cs}") target_sources(offscreen_check PRIVATE tests/startup_sampler_heap.cpp) +# Sampler word decoding, manifest lines and title sampler snapshots behind those draws +# (src/startup_stubs/translated_sampler_bindings.h), without a device. The mutated run is the negative control. +add_executable(startup_translated_sampler_bindings_check tests/startup_translated_sampler_bindings_check.cpp) +target_include_directories(startup_translated_sampler_bindings_check PRIVATE src) +target_compile_features(startup_translated_sampler_bindings_check PRIVATE cxx_std_17) +add_test(NAME startup_translated_sampler_bindings COMMAND startup_translated_sampler_bindings_check) +add_test(NAME startup_translated_sampler_bindings_shared_axis_control + COMMAND startup_translated_sampler_bindings_check --mutate shared-axis) +set_tests_properties(startup_translated_sampler_bindings_shared_axis_control PROPERTIES WILL_FAIL TRUE) target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp) target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp) # Stand-in format for 16-bit packed targets the adapter cannot use (src/startup_stubs/packed_target_format.h). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c8a81a8b3..26559b09e 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -429,6 +429,12 @@ These are measured on one executable; treat them as hypotheses for others. Wrapped sampler heaps keep the 16-byte title stride separate from the desktop descriptor increment for CPU handles and descriptor copies. The source-built readback uses `ctest --preset dev --no-tests=error -R '^startup_sampler_heap_' -V`. + The readback samples only wrap, clamp and border samplers along U. A device-free check covers the + rest of the sampler word decoding (each address mode on each axis, filters, anisotropy and border + colour), the `smpheap` manifest lines that are refused, snapshot counts and unreadable records, and + snapshot equality: build `startup_translated_sampler_bindings_check` and run + `ctest --preset dev --no-tests=error -R "^startup_translated_sampler_bindings(_shared_axis_control)?$" -V`. + The control expects all three axes to use the U field and must fail. - The startup shader translator lowers `image_sample_l` (explicit level, 2D and 3D, any `dmask`) to `SampleLevel(sampler, uv, level)`, taking the level from the last address register. Offset, compare, gather, clamp, cube, 1D and `unorm` forms are refused. Only the translation is checked diff --git a/tests/startup_translated_sampler_bindings_check.cpp b/tests/startup_translated_sampler_bindings_check.cpp new file mode 100644 index 000000000..3393cd3ba --- /dev/null +++ b/tests/startup_translated_sampler_bindings_check.cpp @@ -0,0 +1,291 @@ +// Checks src/startup_stubs/translated_sampler_bindings.h without a device: how 16-byte title sampler +// words decode to desktop samplers, which manifest lines the stand-in accepts, and what a snapshot of +// title sampler memory keeps. +#include "startup_stubs/translated_sampler_bindings.h" + +#include +#include +#include +#include +#include +#include + +namespace { +using namespace x2w_startup; +int failures, cases; +bool shared_axis; // --mutate shared-axis + +void fail(const char* name, const char* what, unsigned got, unsigned expected) +{ + std::printf("FAIL %s: %s 0x%x, expected 0x%x\n", name, what, got, expected); + ++failures; +} + +void expect(const char* name, const char* what, unsigned got, unsigned expected) +{ + if (got != expected) fail(name, what, got, expected); +} + +// D3D12 values written out, not taken from the header's expressions. +enum : unsigned { wrap = 1, mirror = 2, clamp = 3, border = 4, mirror_once = 5 }; +enum : unsigned { + point = 0x0, mip_linear = 0x1, mag_linear = 0x4, min_linear = 0x10, trilinear = 0x15, anisotropic = 0x55 +}; + +// GCN SQ_TEX_CLAMP values 0 to 7: WRAP, MIRROR, CLAMP_LAST_TEXEL, MIRROR_ONCE_LAST_TEXEL, +// CLAMP_HALF_BORDER, MIRROR_ONCE_HALF_BORDER, CLAMP_BORDER, MIRROR_ONCE_BORDER. The desktop has no +// half-border or mirror-once-border mode: the half-border modes keep their edge texel and the last +// becomes BORDER. +constexpr unsigned desktop_mode[8] = {wrap, mirror, clamp, mirror_once, clamp, mirror_once, border, border}; + +// Word 0: CLAMP_X bits 0-2, CLAMP_Y 3-5, CLAMP_Z 6-8, MAX_ANISO_RATIO 9-11. +// Word 2: XY_MAG_FILTER bits 20-21, XY_MIN_FILTER 22-23, Z_FILTER 24-25, MIP_FILTER 26-27. +std::uint32_t word0(unsigned u, unsigned v, unsigned w, unsigned aniso) +{ + return u | v << 3 | w << 6 | aniso << 9; +} + +void decoded(const char* name, const SamplerWords& words, unsigned u, unsigned v, unsigned w, unsigned filter, + unsigned anisotropy, UINT reg = 0) +{ + ++cases; + const int before = failures; + if (shared_axis) v = w = u; + const D3D12_STATIC_SAMPLER_DESC s = decode_sampler(words, reg); + expect(name, "static Filter", s.Filter, filter); + expect(name, "static AddressU", s.AddressU, u); + expect(name, "static AddressV", s.AddressV, v); + expect(name, "static AddressW", s.AddressW, w); + expect(name, "static MaxAnisotropy", s.MaxAnisotropy, anisotropy); + expect(name, "static ComparisonFunc", s.ComparisonFunc, 8); // ALWAYS + expect(name, "static BorderColor", s.BorderColor, 0); // TRANSPARENT_BLACK + expect(name, "static ShaderRegister", s.ShaderRegister, reg); + expect(name, "static RegisterSpace", s.RegisterSpace, 0); + expect(name, "static ShaderVisibility", s.ShaderVisibility, 0); // ALL + if (s.MipLODBias != 0.0f || s.MinLOD != 0.0f || s.MaxLOD != FLT_MAX) fail(name, "static LOD range", 0, 0); + + const D3D12_SAMPLER_DESC d = dynamic_sampler(words); + expect(name, "dynamic Filter", d.Filter, filter); + expect(name, "dynamic AddressU", d.AddressU, u); + expect(name, "dynamic AddressV", d.AddressV, v); + expect(name, "dynamic AddressW", d.AddressW, w); + expect(name, "dynamic MaxAnisotropy", d.MaxAnisotropy, anisotropy); + expect(name, "dynamic ComparisonFunc", d.ComparisonFunc, 8); + for (float component : d.BorderColor) + if (component != 0.0f) fail(name, "dynamic BorderColor", 1, 0); + if (d.MipLODBias != 0.0f || d.MinLOD != 0.0f || d.MaxLOD != FLT_MAX) fail(name, "dynamic LOD range", 0, 0); + if (failures != before) std::printf(" words %08x %08x %08x %08x\n", words[0], words[1], words[2], words[3]); +} + +void manifest(const char* name, std::initializer_list lines, bool accepted, bool heap, bool fallback, + std::size_t statics = 0) +{ + ++cases; + TranslatedSamplers samplers; + bool ok = true; + for (const char* line : lines) ok = samplers.read_manifest_line(line) && ok; + expect(name, "accepted", ok, accepted); + expect(name, "heap", samplers.heap, heap); + expect(name, "reserved_fallback", samplers.reserved_fallback, fallback); + expect(name, "statics", static_cast(samplers.statics.size()), static_cast(statics)); +} + +struct Pages { + unsigned char* base = nullptr; + std::size_t page = 0; + Pages(unsigned readable, unsigned blocked) + { + SYSTEM_INFO system{}; + GetSystemInfo(&system); + page = system.dwPageSize; + base = static_cast( + VirtualAlloc(nullptr, (readable + blocked) * page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + DWORD old = 0; + if (!base || (blocked && !VirtualProtect(base + readable * page, blocked * page, PAGE_NOACCESS, &old))) { + std::printf("FAIL cannot allocate fixture pages\n"); + std::exit(1); + } + } + ~Pages() { VirtualFree(base, 0, MEM_RELEASE); } +}; + +// Record i holds {0x1000 * (i + 1) + 0..3}, so a record read from the wrong place or index differs. +SamplerWords record(UINT i) +{ + const std::uint32_t base = 0x1000 * (i + 1); + return {base, base + 1, base + 2, base + 3}; +} + +void fill(unsigned char* at, UINT records) +{ + for (UINT i = 0; i < records; ++i) { + const SamplerWords words = record(i); + std::memcpy(at + i * 16, words.data(), 16); + } +} + +// readable_end: records [0, readable_end) are readable; the rest of [0, count) are not and are zero. +void snapshot(const char* name, std::uintptr_t address, UINT count, bool reserve, UINT expected_count, + UINT readable_end) +{ + ++cases; + const int before = failures; + const SamplerSnapshot got = snapshot_samplers({address, count}, reserve); + expect(name, "count", got.count, expected_count); + expect(name, "reserved_fallback", got.reserved_fallback, reserve); + expect(name, "readable entries", static_cast(got.readable.count()), readable_end); + for (UINT i = 0; i < 2048 && failures == before; ++i) { + const bool readable = i < readable_end; + expect(name, "readable bit", got.readable.test(i), readable); + const SamplerWords want = readable ? record(i) : SamplerWords{}; + if (got.words[i] != want) { + std::printf("FAIL %s: entry %u holds %08x %08x %08x %08x\n", name, i, got.words[i][0], got.words[i][1], + got.words[i][2], got.words[i][3]); + ++failures; + } + } +} +} // namespace + +int main(int argc, char** argv) +{ + // --mutate shared-axis: the expectations of a decoder that applies the U field to all three axes + // (a negative control: the check must then fail on every case with distinct axes). + shared_axis = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "shared-axis") == 0; + if (argc > 1 && !shared_axis) { + std::printf("unknown mutation\n"); + return 2; + } + + expect("constants", "table entries", translated_sampler_count, 2048); + expect("constants", "table space", translated_sampler_space, 1); + expect("constants", "fallback entry", translated_sampler_fallback, 2047); + expect("constants", "title stride", title_sampler_stride, 16); + expect("root", "sampler table parameter without views", sampler_root_parameter(0), 1); + expect("root", "sampler table parameter with views", sampler_root_parameter(1), 2); + expect("root", "sampler table parameter with four views", sampler_root_parameter(4), 2); + + // Every clamp value on each axis, with the three axes different from one another. + char name[64]; + for (unsigned k = 0; k < 8; ++k) { + std::snprintf(name, sizeof(name), "clamp modes %u %u %u", k, (k + 3) % 8, (k + 6) % 8); + decoded(name, {word0(k, (k + 3) % 8, (k + 6) % 8, 0), 0, 0, 0}, desktop_mode[k], desktop_mode[(k + 3) % 8], + desktop_mode[(k + 6) % 8], point, 1, k); + } + // MAX_ANISO_RATIO n is 2^n samples, at most the desktop's 16. + const unsigned ratios[8] = {1, 2, 4, 8, 16, 16, 16, 16}; + for (unsigned n = 0; n < 8; ++n) { + std::snprintf(name, sizeof(name), "aniso ratio %u", n); + decoded(name, {word0(0, 0, 0, n), 0, 0, 0}, wrap, wrap, wrap, point, ratios[n]); + } + // Filters: point and bilinear choices for magnification, minification and mips; any anisotropic + // XY filter (2 or 3) makes the sampler anisotropic. Mip filter 1 is point. + decoded("point", {0, 0, 0, 0}, wrap, wrap, wrap, point, 1); + decoded("linear mag", {0, 0, 1u << 20, 0}, wrap, wrap, wrap, mag_linear, 1); + decoded("linear min", {0, 0, 1u << 22, 0}, wrap, wrap, wrap, min_linear, 1); + decoded("point mip", {0, 0, 1u << 26, 0}, wrap, wrap, wrap, point, 1); + decoded("linear mip", {0, 0, 2u << 26, 0}, wrap, wrap, wrap, mip_linear, 1); + decoded("trilinear", {0, 0, 1u << 20 | 1u << 22 | 2u << 26, 0}, wrap, wrap, wrap, trilinear, 1); + decoded("anisotropic mag", {0, 0, 2u << 20, 0}, wrap, wrap, wrap, anisotropic, 1); + decoded("anisotropic min", {0, 0, 2u << 22, 0}, wrap, wrap, wrap, anisotropic, 1); + decoded("anisotropic mag 3, ratio 4", {word0(0, 0, 0, 4), 0, 3u << 20, 0}, wrap, wrap, wrap, anisotropic, 16); + // Bits the decoder does not read: word 1, word 3, Z_FILTER and the high bits of words 0 and 2. + decoded("ignored bits", {word0(2, 1, 3, 0) | 0xfffff000u, ~0u, 1u << 22 | 3u << 24 | 0xf0000000u | 0xfffffu, ~0u}, + clamp, mirror, mirror_once, min_linear, 1, 7); + + // The border sampler a missing table entry uses: border on all three axes, point, transparent black. + { + ++cases; + const D3D12_SAMPLER_DESC b = border_sampler(); + expect("border sampler", "Filter", b.Filter, point); + expect("border sampler", "AddressU", b.AddressU, border); + expect("border sampler", "AddressV", b.AddressV, border); + expect("border sampler", "AddressW", b.AddressW, border); + for (float component : b.BorderColor) + if (component != 0.0f) fail("border sampler", "BorderColor", 1, 0); + } + + // Manifest lines. + manifest("table", {"smpheap 2048 1"}, true, true, false); + manifest("table with fallback", {"smpheap 2048 1 fallback 2047"}, true, true, true); + manifest("tab separator", {"smpheap\t2048 1 fallback 2047"}, true, true, true); + manifest("other fallback entry", {"smpheap 2048 1 fallback 2046"}, false, false, false); + manifest("fallback without entry", {"smpheap 2048 1 fallback"}, false, false, false); + manifest("other policy", {"smpheap 2048 1 reserve 2047"}, false, false, false); + manifest("trailing field", {"smpheap 2048 1 fallback 2047 x"}, false, false, false); + manifest("2049 entries", {"smpheap 2049 1"}, false, false, false); + manifest("2047 entries", {"smpheap 2047 1"}, false, false, false); + manifest("space 0", {"smpheap 2048 0"}, false, false, false); + manifest("space 2", {"smpheap 2048 2 fallback 2047"}, false, false, false); + manifest("no space", {"smpheap 2048"}, false, false, false); + manifest("joined keyword", {"smpheap2048 1"}, false, false, false); + manifest("second table", {"smpheap 2048 1", "smpheap 2048 1 fallback 2047"}, false, true, false); + manifest("static samplers", {"smp 0 0x2 0x0 0x100000 0x0", "smp 1 0 0 0 0", "srv 0 tex2d table 0 0"}, true, + false, false, 2); + manifest("short static sampler ignored", {"smp 0 0x2 0x0 0x100000"}, true, false, false, 0); + manifest("statics beside the table", {"smp 0 0 0 0 0", "smpheap 2048 1 fallback 2047"}, true, true, true, 1); + { + ++cases; + TranslatedSamplers samplers; + samplers.read_manifest_line("smp 3 0x2 0xa 0x400000 0xb"); + if (samplers.statics.size() != 1 || samplers.statics[0] != SamplerWords{2, 0xa, 0x400000, 0xb}) + fail("static sampler words", "words", 0, 0); + } + + // Snapshots. Record i is 0x1000 * (i + 1) + 0..3. + { + Pages pages(9, 0); + fill(pages.base, 2048); + const auto at = reinterpret_cast(pages.base); + snapshot("three records", at, 3, false, 3, 3); + snapshot("full table", at, 2048, false, 2048, 2048); + snapshot("full table, reserved entry", at, 2048, true, 2047, 2047); + snapshot("count above the table", at, 5000, false, 2048, 2048); + snapshot("count above the table, reserved entry", at, 5000, true, 2047, 2047); + snapshot("no records", at, 0, true, 0, 0); + snapshot("null address", 0, 3, true, 0, 0); + snapshot("table past the top of memory", UINTPTR_MAX - 2048 * 16 + 1, 1, false, 0, 0); + // A table that ends exactly at the top is read; that kernel address is unreadable. + snapshot("table ending at the top of memory", UINTPTR_MAX - 2048 * 16, 1, false, 1, 0); + // Not 16-byte aligned: runs still stop at page ends and read whole records. + fill(pages.base + 8, 600); + snapshot("unaligned records across pages", at + 8, 600, false, 600, 600); + } + { + // Two readable records end 8 bytes before an inaccessible page. The third crosses into it + // and the fourth lies inside it; both are unreadable and zero. + Pages pages(1, 1); + unsigned char* const begin = pages.base + pages.page - 40; + fill(begin, 2); + std::memcpy(begin + 32, record(2).data(), 8); // the readable half of record 2 + snapshot("records up to an inaccessible page", reinterpret_cast(begin), 4, false, 4, 2); + } + { + // A draw reuses its sampler table only when the new snapshot equals the last one, so each + // field on its own must make two snapshots differ. + ++cases; + Pages pages(1, 0); + fill(pages.base, 4); + const SamplerSource source{reinterpret_cast(pages.base), 4}; + const SamplerSnapshot first = snapshot_samplers(source, false); + if (!(snapshot_samplers(source, false) == first)) fail("equal snapshots", "equal", 0, 1); + pages.base[3 * 16 + 8] ^= 1; // one bit of record 3, word 2 + if (snapshot_samplers(source, false) == first) fail("changed sampler word", "equal", 1, 0); + SamplerSnapshot other = first; + other.readable.reset(1); + if (other == first) fail("changed readable bit", "equal", 1, 0); + other = first; + other.count = 3; + if (other == first) fail("changed count", "equal", 1, 0); + other = first; + other.reserved_fallback = true; + if (other == first) fail("changed reserved entry", "equal", 1, 0); + } + + if (failures) { + std::printf("startup_translated_sampler_bindings: %d FAILED in %d cases\n", failures, cases); + return 1; + } + std::printf("startup_translated_sampler_bindings: PASS (%d cases)\n", cases); + return 0; +} From f500398e9de5d1f53d13ff5d042150ca3335c287 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:39:33 +0100 Subject: [PATCH 115/775] tests: keep the suffix-order fences alive until the worker has signaled them --- tests/startup_storage_worker_start.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/startup_storage_worker_start.cpp b/tests/startup_storage_worker_start.cpp index c30518cab..6ebb49511 100644 --- a/tests/startup_storage_worker_start.cpp +++ b/tests/startup_storage_worker_start.cpp @@ -622,6 +622,10 @@ bool suffix_waits_for_prefix(Fixture& f) if (!q.queue->work || q.queue->work->waiting.empty() || !has_unrecorded(q.queue)) { hold_prefix = false; f.submit(q); + // The fences are locals the worker still signals: wait until it is done with them. + const DWORD start = GetTickCount(); + while ((prefix_fence.signals == 0 || suffix_fence.signals == 0) && GetTickCount() - start < completion_timeout_ms) + Sleep(1); continue; } ++suffix_cases; From a8815ee61e771fdad7bae1768e212b451ca19744 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 20:41:27 +0800 Subject: [PATCH 116/775] shader: lower gfx1030 image atomic arithmetic and bitwise operations --- CMakeLists.txt | 5 ++ README.md | 1 + docs/experiments.md | 48 +++++++++++++ tests/compute_check.cpp | 37 +++++++--- tests/compute_store_check.py | 134 +++++++++++++++++++++++++++++++++++ tests/offscreen_check.cpp | 2 +- tools/compute_store_aot.py | 52 +++++++++++--- 7 files changed, 259 insertions(+), 20 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f0197e53..631397515 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5723,6 +5723,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mimg_store_packed_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mimg_store_packed_${adapter}.txt") + add_test(NAME compute_store_aot_mimg_atomic_integer_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mimg-atomic-integer "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_mimg_atomic_integer_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mimg_atomic_integer_${adapter}.txt") add_test(NAME compute_store_aot_ds_route_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-ds-route "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 1f3967100..b183cd30a 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 image queries | Lower [2D mip dimensions and level count](docs/experiments.md#gfx1030-2d-image-resource-queries) for `image_get_resinfo`. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_resinfo_'` | | gfx1030 MSAA image load | Lower [`image_msaa_load` for 4× `R32_UINT` 2D input](docs/experiments.md#gfx1030-4-sample-image-load). Compare the four samples per pixel and the untouched UAV words against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_msaa_'` | | gfx1030 image stores | Lower [typed RGBA32 and packed RGBA8 2D writes](docs/experiments.md#gfx1030-2d-image-stores), including fixed explicit mip levels and sparse `dmask` values. Compare all mip levels against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_store_'` | +| gfx1030 image atomics | Lower [non-returning add, subtract and bitwise atomics on scalar 2D UAVs](docs/experiments.md#gfx1030-2d-integer-image-atomics). Compare all mips and include a contended add case. | `ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_mimg_atomic_integer_'` | | gfx1030 formatted D16 UINT reads | Lower [indexed `buffer_load_format_d16_*` with caller-declared RGBA16 UINT](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-reads) and verify packed channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_load_format_d16_'` | | gfx1030 raw D16 reads | Lower [indexed D16 byte and short MUBUF loads](docs/experiments.md#indexed-gfx1030-raw-d16-reads) and verify that the other VGPR half stays unchanged. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_d16_'` | | gfx1030 formatted UINT buffer reads | Lower [indexed `buffer_load_format_*` with caller-declared RGBA32 UINT](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-reads) and verify one to four channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_format_'` | diff --git a/docs/experiments.md b/docs/experiments.md index d7e8e7546..a7f5409e0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3383,6 +3383,54 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_store_(packed_)?(warp|hardware)$' -V ``` +### gfx1030 2D integer image atomics + +The compute store profile lowers one unguarded 32-bit `image_atomic_*` +instruction per `gfx1030` shader, with `glc` clear, one 32-bit data VGPR, +a contiguous pair of 32-bit X/Y coordinate VGPRs, and optional `unorm`. +The caller supplies in-bounds coordinates and declares a scalar `R32_UINT` +2D image with identity channel selectors and binds its matching UAV to +`u0` at mip 0. The eight resource words must be loaded from the declared table +offset and ready at issue. The translator tracks the descriptor's provenance. +The caller supplies its format, layout and bounds. Other address widths, +dimensions, cache flags, returned values and additional UAV accesses are outside +this profile. See sections 8.2 and 12.16 of the +[AMD RDNA 2 ISA](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture). + +| Native suffixes | Desktop `cs_6_0` operation and view | +|---|---| +| `add`, `sub` | `InterlockedAdd`, `R32_UINT`, negate the subtract operand modulo 2^32 | +| `and`, `or`, `xor` | Matching `Interlocked` bitwise intrinsic, `R32_UINT` | + +`DMASK` is `0x1`. The +[format support query](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_format_support2) +gates the typed atomic operations for each view. An unavailable capability +returns 77. The GPU fixture compares 336 words over all three mips of a +32x8 texture per case, including untouched words. One- and two-group draws +exercise high-bit inputs, arithmetic wraparound and two lanes adding to +each texel in the contended add case. Lowering subtract as add must fail +first at mip 0, word 32. The test records the five forms only after all +positive and negative dispatch checks complete. + +The LLVM 15 test assembles, disassembles and translates the cases through the +synthetic-container CLI. The standalone compile mode checks the generated +`cs_6_0` shaders and the subtract mutation without adapter access. The GPU +tests are the translated DXIL comparison against the CPU reference. Run these +serially after coordinating adapter access. + +```powershell +$Dxc = (Get-Command dxc -ErrorAction Stop).Source +$env:TMP = (Resolve-Path out).Path +$env:TEMP = $env:TMP +python -B tests/compute_store_check.py compile-mimg-atomic-integer $Dxc +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_mimg_atomic_integer_(warp|hardware)$' -V +``` + +```bash +python3 -B tests/compute_store_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 +``` + ### Bounded gfx1030 DS lane routing The `gfx1030` compute profile lowers `ds_bpermute_b32` (gather) and diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index 3243baae0..752ff7119 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -22,9 +22,11 @@ static_assert(constants_offset % alignment == 0); constexpr UINT sentinel = 0xc5c5c5c5u; constexpr std::array constants{count, 73, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 23, 29}; constexpr UINT uavs = 13, srvs = 21; -// Bit 24 of an image case's dispatch word selects RGBA8 instead of RGBA32. -// The case file carries the raw texels for either format. +// The image case header packs the dispatch count and a format selector. The payload +// carries raw texels, one word each for RGBA8 and scalar R32, or four for RGBA32. constexpr UINT texture_rgba8_flag = 1u << 24; +constexpr UINT texture_atomic_uint_flag = 1u << 25; +constexpr UINT texture_format_mask = texture_rgba8_flag | texture_atomic_uint_flag; constexpr UINT texture_width = 32, texture_height = 8, texture_channels = 4; constexpr UINT texture_mip_levels = 3; } @@ -54,7 +56,7 @@ static ComPtr upload_texture(ID3D12Device* device, ID3D12Graphic const std::vector& texels, DXGI_FORMAT format, ComPtr& staging, bool writable = false) { - const UINT words_per_texel = format == DXGI_FORMAT_R8G8B8A8_UINT ? 1 : texture_channels; + const UINT words_per_texel = format == DXGI_FORMAT_R32G32B32A32_UINT ? texture_channels : 1; const UINT base_words = texture_width * texture_height * words_per_texel; const UINT mips = texels.size() == base_words ? 1 : texture_mip_levels; D3D12_RESOURCE_DESC desc{}; @@ -410,22 +412,39 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co std::ifstream source(reference, std::ios::binary); source.read(reinterpret_cast(&groups), sizeof(groups)); source.read(reinterpret_cast(&mip), sizeof(mip)); - const bool rgba8 = (groups & texture_rgba8_flag) != 0; - groups &= ~texture_rgba8_flag; - const auto format = rgba8 ? DXGI_FORMAT_R8G8B8A8_UINT : DXGI_FORMAT_R32G32B32A32_UINT; - const UINT words_per_texel = rgba8 ? 1 : texture_channels; + const UINT selector = groups & texture_format_mask; + groups &= ~texture_format_mask; + DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_UINT; + UINT required = D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE; + switch (selector) { + case 0: break; + case texture_rgba8_flag: format = DXGI_FORMAT_R8G8B8A8_UINT; break; + case texture_atomic_uint_flag: + format = DXGI_FORMAT_R32_UINT; + required = D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD | + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS; + break; + default: throw std::runtime_error("Invalid compute image store format selector"); + } + const UINT words_per_texel = selector ? 1 : texture_channels; const UINT base_words = texture_width * texture_height * words_per_texel; const UINT all_words = base_words + base_words / 4 + base_words / 16; std::vector initial(all_words), expected(all_words); source.read(reinterpret_cast(initial.data()), all_words * sizeof(UINT)); source.read(reinterpret_cast(expected.data()), all_words * sizeof(UINT)); - if (!source || source.peek() != std::char_traits::eof() || !groups || groups > 2 || mip >= texture_mip_levels) + if (!source || source.peek() != std::char_traits::eof() || !groups || groups > 2 || mip >= texture_mip_levels + || (selector == texture_atomic_uint_flag && mip != 0)) throw std::runtime_error("Invalid compute image store reference"); D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; check(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support)), "Check texture UAV format"); - if (!(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) return false; + if ((support.Support2 & required) != required) { + std::printf("format=%u required_support2=0x%x support1=0x%x support2=0x%x\n", + static_cast(format), required, static_cast(support.Support1), + static_cast(support.Support2)); + return false; + } const auto code = read_texture_shader(path); ComPtr signature; diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index ee8ff1177..3a2a21ce2 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -3331,6 +3331,10 @@ def binary(directory, assembler, objcopy, library): gfx1030_binary(directory, assembler, objcopy, library, [(name, lines, MIMG_BINDING) for name, _, _, _, _, lines in mimg_resinfo_cases()], "image_get_resinfo", group=(8, 8, 1)) + mimg_atomic_controls() + gfx1030_binary(directory, assembler, objcopy, library, + [(f"image_atomic_{name}", lines, binding) for name, _, lines, binding in mimg_atomic_cases()], + "image_atomic_", group=MIMG_STORE_GROUP) mimg_store_controls() gfx1030_binary(directory, assembler, objcopy, library, [(name, lines, binding) for name, _, _, lines, binding in mimg_store_cases()], @@ -4795,6 +4799,134 @@ def mimg_resinfo_draw(directory, compiler, renderer, backend): return 0 +MIMG_ATOMIC_UINT_FLAG = 1 << 25 +MIMG_ATOMIC_BEFORE = (0xfffffff0, 0x7ffffff0, 0x20, 0x80000000) +MIMG_ATOMIC_VALUE = 0x80000011 + + +def mimg_atomic_cases(): + binding = MIMG_STORE_BINDING | {"image_uav_mip": 0, "image_format": "R32_UINT"} + for op in ("add", "sub", "and", "or", "xor"): + for contended in ((False, True) if op == "add" else (False,)): + lines = ["s_mov_b32 s12, s7", "s_mov_b32 s13, 0", + "s_load_dwordx8 s[24:31], s[12:13], 0x40", + "v_lshl_add_u32 v8, s10, 2, v0", + "v_mov_b32_e32 v9, 1" if contended else "v_lshl_add_u32 v9, s11, 1, v1"] + if not contended: + lines.append("v_add_nc_u32_e32 v9, 1, v9") + lines.append(f"v_mov_b32_e32 v14, {MIMG_ATOMIC_VALUE:#x}") + flags = " unorm" if contended else "" + lines += ["s_waitcnt lgkmcnt(0)", + f"image_atomic_{op} v14, v[8:9], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D{flags}", + "s_waitcnt_vscnt null, 0x0", "s_endpgm"] + yield op + ("_contended" if contended else ""), contended, lines, binding + + +def mimg_atomic_controls(): + cases = {op: (lines, binding) for op, _, lines, binding in mimg_atomic_cases()} + lines, binding = cases["add"] + instruction = lines[-3] + for changed, diagnostic in ( + (instruction.replace("dmask:0x1", "dmask:0xf"), "Unverified image atomic data range or mask"), + (instruction.replace("dmask:0x1", "dmask:0x3"), "Unverified image atomic data range or mask"), + (instruction.replace("v14", "v256"), "Unverified image atomic data range or mask"), + (instruction.replace("v14", "v15"), "Unverified image atomic data"), + (instruction.replace("v14", "v[14:15]"), "Unsupported compute instruction"), + (instruction.replace("v[8:9]", "v[8:10]"), "Unverified image atomic coordinates"), + (instruction.replace("v[8:9]", "v[9:10]"), "Unverified image atomic coordinates"), + (instruction.replace("s[24:31]", "s[28:35]"), "Unverified image atomic descriptor"), + (instruction + "\n" + instruction, "Unsupported image atomic target or binding"), + (instruction.replace("IMG_2D", "IMG_2D_ARRAY"), "Unsupported compute instruction"), + (instruction.replace("v[8:9]", "[v8, v9]"), "Unsupported compute instruction"), + *((instruction + flag, "Unsupported compute instruction") + for flag in (" glc", " dlc", " slc", " a16", " d16", " tfe", " lwe", " r128")), + ): + rejects(diagnostic, aot.lower, variant(lines, (instruction, changed)), MIMG_STORE_GROUP, **binding) + rejects("Unverified image atomic descriptor", aot.lower, + lines[:-4] + lines[-3:], MIMG_STORE_GROUP, **binding) + rejects("Unsupported image atomic target or binding", aot.lower, lines, MIMG_STORE_GROUP, + **(binding | {"image_format": "R32G32B32A32_UINT"})) + rejects("Invalid image UAV binding", aot.lower, lines, MIMG_STORE_GROUP, + **(binding | {"image_uav_mip": 1})) + srv_binding = {key: value for key, value in binding.items() if key != "image_uav_mip"} + rejects("Unsupported image atomic target or binding", aot.lower, lines, MIMG_STORE_GROUP, + **(srv_binding | {"descriptor_offset": MIMG_BINDING["descriptor_offset"]})) + msaa = "image_msaa_load v[14:17], v[8:10], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm" + rejects("requires an unguarded R32_UINT MSAA binding", aot.lower, + variant(lines, (instruction, msaa)), MIMG_STORE_GROUP, **binding) + rejects("Invalid image UAV binding", aot.lower, lines, MIMG_STORE_GROUP, **(binding | {"cpu": "gfx1013"})) + rejects("Invalid image UAV binding", aot.lower, lines, MIMG_STORE_GROUP, + **(binding | {"image_format": "R32_SINT"})) + for op in ("swap", "cmpswap", "smin", "smax", "umin", "umax", "inc", "dec", "fcmpswap", "fmin", "fmax"): + rejects("Unsupported compute instruction", aot.lower, + variant(lines, ("image_atomic_add", "image_atomic_" + op)), MIMG_STORE_GROUP, **binding) + rejects("Unsupported image store target", aot.lower, + variant(lines, ("image_atomic_add", "image_store")), MIMG_STORE_GROUP, **binding) + + +def mimg_atomic_reference(op, contended, groups): + value = MIMG_ATOMIC_VALUE + update = {"add": lambda old: old + value, "sub": lambda old: old - value, + "and": lambda old: old & value, "or": lambda old: old | value, "xor": lambda old: old ^ value}[op] + initial, expected = [], [] + for level in range(3): + for y in range(TEXTURE_HEIGHT >> level): + for x in range(TEXTURE_WIDTH >> level): + before = 0xc0000000 | (level << 20) | (y << 12) | x + after = before + if level == 0 and x < groups * MIMG_STORE_GROUP[0] and y in ((1,) if contended else (1, 2)): + before = MIMG_ATOMIC_BEFORE[(x + y - 1) % len(MIMG_ATOMIC_BEFORE)] + after = update(before) + if contended: + after = update(after) + initial.append(before) + expected.append(after & 0xffffffff) + return initial, expected + + +def mimg_atomic_integer(directory, compiler, renderer=None, backend=None): + mimg_atomic_controls() + record_path = os.environ.get("FORM_COVERAGE_RECORD") if renderer else None + record = Path(record_path) if record_path else None + if record: + record.unlink(missing_ok=True) + completed = set() + for name, contended, lines, binding in mimg_atomic_cases(): + src, cso, case = (directory / f"image_atomic_{name}.{ext}" for ext in ("hlsl", "cso", "case")) + code = aot.lower(lines, MIMG_STORE_GROUP, **binding) + src.write_text(code, encoding="ascii") + compile_shader = [compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src] + subprocess.run(compile_shader, check=True) + op = name.removesuffix("_contended") + for groups in (1, 2): + initial, expected = mimg_atomic_reference(op, contended, groups) + assert len(initial) == len(expected) == 336 and initial != expected + if renderer: + dispatch = groups | MIMG_ATOMIC_UINT_FLAG + case.write_bytes(struct.pack("<674I", dispatch, 0, *initial, *expected)) + run = [renderer, backend, "--compute-texture-store-case", cso, case] + print(f"image_atomic_{name} groups={groups}", flush=True) + result = subprocess.run(run) + if result.returncode: + return result.returncode + if op == "sub": + correct, wrong = f"(0u - {MIMG_ATOMIC_VALUE:#010x}u)", f"{MIMG_ATOMIC_VALUE:#010x}u" + mismatch = "mip=0 word=32 expected=7fffffdf actual=80000001" + assert code.count(correct) == 1 + src.write_text(code.replace(correct, wrong), encoding="ascii") + subprocess.run(compile_shader, check=True) + if renderer: + bad = subprocess.run(run, capture_output=True, text=True) + if bad.returncode != 1 or mismatch not in bad.stderr: + raise AssertionError(f"{name}: wrong atomic operand escaped detection\n{bad.stderr}") + print(f"{name} wrong atomic operand: {bad.stderr}", end="") + completed.add(f"image_atomic_{op}") + if record: + record.parent.mkdir(parents=True, exist_ok=True) + record.write_text("\n".join(sorted(completed)) + "\n", encoding="utf-8") + return 0 + + def mimg_mip_draw(directory, compiler, renderer, backend): return mimg_load_draw(directory, compiler, renderer, backend, mip=True) @@ -5472,6 +5604,8 @@ def draw(directory, compiler, renderer, backend, cases=None): "draw-mimg-resinfo": mimg_resinfo_draw, "draw-mimg-packed": mimg_packed_draw, "draw-mimg-store": mimg_store_draw, + "compile-mimg-atomic-integer": lambda d, compiler: mimg_atomic_integer(d, compiler), + "draw-mimg-atomic-integer": mimg_atomic_integer, "draw-mimg-packed-store": lambda d, *a: mimg_store_draw(d, *a, packed=True), "draw-ds-route": ds_draw, "draw-lds-qword": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_QWORD_CASES), diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index fff742201..0f49911c6 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -522,7 +522,7 @@ OperationResult run_compute_texture_msaa_case(const OperationContext& ctx) OperationResult run_compute_texture_store_case(const OperationContext& ctx) { return skip_if_false(check_compute_texture_store_file(ctx.device, ctx.argv[3], ctx.argv[4]), - "Typed UAV store unavailable for the image case format"); + "Required typed UAV operations unavailable for the image case format"); } OperationResult run_spirv_sampler_views(const OperationContext& ctx) diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index a0bb1fff8..5b94dfdf8 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -78,7 +78,7 @@ # loaded from, not the 9-bit GFX10 format, type, swizzle, level or size fields inside them; the two # 16-byte descriptor slots are bound to t0 for reads or u0 for writes. # Value: (HLSL texel type, channel count). -IMAGE_FORMATS = {"R32G32B32A32_UINT": ("uint4", 4), "R8G8B8A8_UINT": ("uint4", 4), "R32_UINT": ("uint", 1)} +IMAGE_FORMATS = {"R32G32B32A32_UINT": ("uint4", 4), "R8G8B8A8_UINT": ("uint4", 4)} # Template operands are the old LDS word and the source VGPR, both HLSL uints. LDS_RMW = { "ds_add_u32": "({0} + {1})", @@ -99,6 +99,8 @@ "swap": "Exchange", "cmpswap": "CompareExchange", } +IMAGE_ATOMIC_OPS = "add|sub|and|or|xor" + def checked_group(group): """Return (x, y, z) within the D3D12 cs_6_0 numthreads limits.""" @@ -208,8 +210,9 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N for formatted MUBUF stores. Both declarations require identity channel selectors. image_descriptor is the table byte offset of the 8-dword image descriptor. image_format is the caller's statement of the image format inside it. The image binds to t0 for loads or u0 - for stores, where image_uav_mip selects the writable subresource and replaces descriptor_offset. - R32_UINT declares the 4-sample Texture2DMS profile for image_msaa_load. + for writes, where image_uav_mip selects the writable subresource and replaces descriptor_offset. + R32_UINT selects the 4-sample Texture2DMS profile for an SRV or the + non-returning 2D integer atomic profile for a UAV. """ dims = checked_group(group) if cpu not in ("gfx1013", "gfx1030"): @@ -218,12 +221,14 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if not 0 <= table_reg <= 105: raise ValueError("Invalid table or thread group binding") image_output = image_uav_mip is not None - image_msaa = image_format == "R32_UINT" + image_msaa = not image_output and image_format == "R32_UINT" if image_msaa and cpu != "gfx1030": raise ValueError("The R32_UINT MSAA image binding requires gfx1030") + image_atomic = image_output and image_format == "R32_UINT" if image_output: if (cpu != "gfx1030" or descriptor_offset is not None or stride is not None - or image_descriptor is None or image_format not in ("R32G32B32A32_UINT", "R8G8B8A8_UINT") + or image_descriptor is None or (image_format not in IMAGE_FORMATS and not image_atomic) + or (image_atomic and image_uav_mip != 0) or not 0 <= image_uav_mip <= 15): raise ValueError("Invalid image UAV binding") descriptor_bindings = {} @@ -250,7 +255,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unsupported formatted source binding") if image_descriptor is not None or image_format is not None: # The 8-dword image descriptor occupies two 16-byte slots. - if (image_format not in IMAGE_FORMATS or image_descriptor is None or source_descriptor is not None + if (not (image_format in IMAGE_FORMATS or image_msaa or image_atomic) + or image_descriptor is None or source_descriptor is not None or not 0 <= image_descriptor < 1 << 20 or image_descriptor % 4 or any(image_descriptor + half in descriptor_bindings for half in (0, 16)) or any(abs(image_descriptor + half - offset) < 16 @@ -1219,6 +1225,32 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N vector.pop(reg, None) loading[reg] = ("alu", name) image_step_count += 1 + elif m := re.fullmatch(rf"image_atomic_(?P{IMAGE_ATOMIC_OPS}) v(?P\d+), " + r"v\[(?P\d+):(?P\d+)\], s\[(?P\d+):(?P\d+)\] " + r"dmask:0x(?P[0-9a-f]+) dim:SQ_RSRC_IMG_2D(?: unorm)?", line): + op = m["op"] + if not image_atomic or guard_span is not None or stores: + raise ValueError("Unsupported image atomic target or binding") + data = int(m["data"]) + if int(m["mask"], 16) != 1 or data > 255: + raise ValueError("Unverified image atomic data range or mask") + base, high = int(m["base"]), int(m["high"]) + if (high != base + 7 or base % 4 or pending.intersection(range(base, high + 1)) + or tuple(scalar.get(base + index) for index in range(8)) != tuple( + (("image", index // 4), index % 4) for index in range(8))): + raise ValueError("Unverified image atomic descriptor") + x, y = int(m["x"]), int(m["y"]) + coords = [vector.get(reg) for reg in (x, y)] + if y != x + 1 or y > 255 or not all(map(is_word, coords)): + raise ValueError("Unverified image atomic coordinates") + source = vector.get(data) + if not is_word(source): + raise ValueError("Unverified image atomic data") + destination = f"outputData[uint2({', '.join(map(hlsl_word, coords))})]" + value = hlsl_word(source) + if op == "sub": + value = f"(0u - {value})" + stores.append(f" Interlocked{MUBUF_ATOMIC_METHODS[op]}({destination}, {value});") elif m := re.fullmatch(r"image_(?Pload|store|get_resinfo)(?P_mip)?(?P_pck(?:_sgn)?)? " r"(?Pv\d+|v\[\d+:\d+\]), (?Pv\d+|v\[\d+:\d+\]), " r"s\[(?P\d+):(?P\d+)\] dmask:0x(?P[0-9a-f]+) " @@ -1236,7 +1268,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N count = len(channels) data = [int(n) for n in re.findall(r"\d+", m["data"])] first, last = data[0], data[-1] - if (cpu != "gfx1030" or image_format is None or image_msaa or guard_span is not None or write != image_output + if (cpu != "gfx1030" or image_format not in IMAGE_FORMATS or guard_span is not None or write != image_output or len(vaddr) != min(address_words, 2) or vaddr[-1] != vaddr[0] + address_words - 1 or vaddr[-1] > 255 or last != first + count - 1 or not 0 < dmask < (1 << IMAGE_FORMATS[image_format][1]) @@ -1503,7 +1535,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N local = ", uint3 local : SV_GroupThreadID" # Helpers are selected from the final body, so a float ALU result used only by a DS step still gets its definition. cbuffer += "".join(text for name, text in F32_HELPERS.items() if f"f32_{name}(" in body) - uav = "RWTexture2D" if image_output else "RWByteAddressBuffer" + uav = f"RWTexture2D<{'uint' if image_atomic else 'uint4'}>" if image_output else "RWByteAddressBuffer" return (f"{cbuffer}{uav} outputData : register(u0);\n[numthreads({dims[0]},{dims[1]},{dims[2]})]\n" f"void main(uint3 tid : SV_DispatchThreadID{local}) {{\n{body}\n}}\n") @@ -1537,8 +1569,8 @@ def main(): help="Table byte offset of the 8-dword image descriptor bound to t0 or u0") parser.add_argument("--image-uav-mip", type=int, help="Bind the image to u0 at this mip instead of binding a raw output descriptor") - parser.add_argument("--image-format", choices=sorted(IMAGE_FORMATS), - help="Caller-declared image format (R32_UINT selects the 4-sample image_msaa_load profile)") + parser.add_argument("--image-format", choices=sorted(IMAGE_FORMATS.keys() | {"R32_UINT"}), + help="Caller-declared image format (R32_UINT selects MSAA for an SRV or atomics for a UAV)") args = parser.parse_args() if (args.descriptor_offset is None) == (args.image_uav_mip is None): parser.error("Choose either --descriptor-offset or --image-uav-mip") From bbdd7a1a46613ec2ea4e80ff396e4600f62fe28e Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:41:43 +0100 Subject: [PATCH 117/775] docs: mark xapu zero result as placeholder, note handle and memory behavior --- docs/startup-runtime.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c33c67a01..14eb06938 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -503,7 +503,9 @@ and `XApuDisconnect`, refuses null outputs (`E_POINTER`) and unknown or disconne handles (`E_HANDLE`), and queues one completion entry per `XApuEnqueueCommand` call so `XApuGetResultCount` and `XApuDequeueResult` retire commands cleanly (zeroing the `0x58`-byte result buffer without fabricating unmeasured fields, and returning `E_FAIL` -when the queue is empty). Default non-permissive mode still traps on every export +when the queue is empty). The all-zero result is a placeholder: its type field (`+0`) is not a measured +completion value, and no caller has been observed consuming it. Entries are counters only, so memory does +not grow per command. Handles are never reused. Default non-permissive mode still traps on every export (`ctest --preset dev --no-tests=error -R '^startup_xapu_queue$' -V`). `src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the From 0400187aa71257e5d9953779af8aceef789a74b9 Mon Sep 17 00:00:00 2001 From: Joacoorandom <62301477+Joacoorandom@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:41:58 -0300 Subject: [PATCH 118/775] runtime: preflight Windows system commit headroom before PE launch --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 2 + docs/experiments.md | 28 ++++++++ tests/host_commit_check.py | 127 ++++++++++++++++++++++++++++++++++ tools/host_commit.py | 72 +++++++++++++++++++ tools/pe_run_package.py | 13 ++++ 7 files changed, 244 insertions(+) create mode 100644 tests/host_commit_check.py create mode 100644 tools/host_commit.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ca992ab00..177dd3407 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -91,6 +91,7 @@ jobs: python -B tests/layout_chunks_check.py python -B tests/dependency_paths_check.py python -B tests/pe_package_preflight_check.py + python -B tests/host_commit_check.py python -B tests/pe_package_ordinal_plan_check.py python -B tests/compat_report_check.py python -B tests/intake/paths_check.py diff --git a/AGENTS.md b/AGENTS.md index 8123a2110..aedd29614 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -121,6 +121,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/layout_chunks_check.py ./out/pe-env/bin/python -B tests/dependency_paths_check.py ./out/pe-env/bin/python -B tests/pe_package_preflight_check.py +./out/pe-env/bin/python -B tests/host_commit_check.py ./out/pe-env/bin/python -B tests/pe_package_ordinal_plan_check.py ./out/pe-env/bin/python -B tests/compat_report_check.py ./out/pe-env/bin/python -B tests/intake/paths_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c68580f9b..7a6d7186e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6293,6 +6293,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/dependency_paths_check.py") add_test(NAME pe_package_import_closure COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_package_preflight_check.py") + add_test(NAME pe_host_commit_preflight COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/host_commit_check.py") add_test(NAME xgameruntime_preflight_stub_refused COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xgameruntime_preflight_check.py" "$" "$" diff --git a/docs/experiments.md b/docs/experiments.md index 5407b0597..693c5547d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -108,6 +108,34 @@ A maintainer outside this project measured one compile at 3.51 s without the cac including ordinal-only (`NONAME`) DLL exports and forwarder chains ending in an ordinal, using `pe_map_export_ordinal` on the mapped provider. `cpu_native_startup` checks the same two-DLL fixture under this runner and the Windows loader. +**Windows system commit preflight (optional).** When mapping a large source-built +package, use `--min-commit-mib N` with `pe_run_package.py` to read the system +commit budget through `GetPerformanceInfo` **before** the package is inspected +or any external provider is loaded. It refuses an insufficient budget with a +plain-language error instead of reaching an out-of-commit mapper failure. +The check uses `CommitLimit - CommitTotal` times the Windows page size, *not* +physical free RAM; system commit includes paging-file backing. `N=0` requests +an informational snapshot only. The JSON result adds `host_commit` with the +limit, used, available and requested MiB only when the option is present. +No default minimum is imposed because the amount a package needs is unknown. +The snapshot reserves no memory: another process can consume the headroom +before or during startup, so a successful check is not a startup guarantee. + +```powershell +python -B tools/pe_run_package.py pe_map.dll out/source-built-package app.exe --min-commit-mib 4096 --preflight-only +python -B tests/host_commit_check.py -v +``` + +This is independently written from public Windows PSAPI behavior and the +reported Windows commit-limit failure mode in +[VIctory's README at `ffe310e`](https://github.com/Marvisak/VIctory/blob/ffe310eb2098e52169f4c44db5ffdabf43a72622/README.md). +No VIctory (GPL-3.0-or-later) source code is copied into this MIT project. +The source-built Linux tests mock the Windows API and check limits, underflow, +API errors, low-commit failure **before** package inspection, and preservation +of the prior JSON output when the option is absent. The native Windows test +uses the real `GetPerformanceInfo` API; it validates the live response but +requires no title files or allocations. + External providers with process-lifetime workers can use `--pin-shim DLL` alongside `--shim DLL PATH`. This pins the provider immediately before the first guest image loads, and only in execution mode. Run packages in a child process when using pinned providers. The guest must still join its own workers and quiesce any host calls into guest code before returning. `cpu_package_shim_lifetime` verifies that the selected provider remains loaded after the entry returns and the ordinary provider unloads. `--trap-callable DLL!SYMBOL` (or `DLL!#ORDINAL`, repeatable) is a diagnostic execution mode for finding the last startup stage a package reaches. By default the runner refuses any unresolved external before mapping. An import table entry names a symbol, but it does not say whether the caller calls it or reads it as data, so this mode binds only the unresolved externals the caller lists as callable. Each listed name gets a numbered trap, and the traps are listed on stderr in sorted `dll!symbol` order. Any unlisted unresolved external is still refused before mapping, and so is a listed name that is not an unresolved external. A trap never returns: it prints `trap N: : !` and terminates the process with `0xE7A00000 | N`. The report is best effort, and termination does not depend on it. No DLL is written or loaded under the missing name, and a trap is not a provider. If the entry returns without reaching a trap, the JSON result adds `unhit_traps`. The option cannot be combined with `--preflight-only`, and `plan(report, allow_external=False)` still refuses the same package. diff --git a/tests/host_commit_check.py b/tests/host_commit_check.py new file mode 100644 index 000000000..82be919a1 --- /dev/null +++ b/tests/host_commit_check.py @@ -0,0 +1,127 @@ +"""Windows commit-budget controls with fake OS counters; no title data or Windows required.""" + +import ctypes +import io +import json +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import patch +from contextlib import redirect_stderr, redirect_stdout + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +from host_commit import MIB, PerformanceInformation, read_host_commit, require_commit_budget, snapshot_from_pages +import pe_run_package + + +class NativeGetPerformance: + def __init__(self, *, limit=1000, used=600, size=65536, success=True): + self.limit, self.used, self.size, self.success = limit, used, size, success + self.argtypes = None + self.restype = None + self.seen = [] + + def __call__(self, pointer, capacity): + info = ctypes.cast(pointer, ctypes.POINTER(PerformanceInformation)).contents + self.seen.append((info.cb, capacity)) + if self.success: + info.CommitLimit, info.CommitTotal, info.PageSize = self.limit, self.used, self.size + return int(self.success) + + +class HostCommitChecks(unittest.TestCase): + def test_page_budget_and_zero_floor(self): + exact = snapshot_from_pages(128, 96, MIB) + self.assertEqual(exact, dict(limit_mib=128, used_mib=96, available_mib=32, + available_bytes=32 * MIB)) + self.assertTrue(require_commit_budget(32, exact)["meets_minimum"]) + with self.assertRaisesRegex(ValueError, "below the requested 33 MiB"): + require_commit_budget(33, exact) + self.assertEqual(snapshot_from_pages(2, 3, MIB)["available_bytes"], 0) + self.assertEqual(snapshot_from_pages(3, 2, 4096)["available_mib"], 0) + for args in ((0, 0, 4096), (1, 0, 0)): + with self.assertRaisesRegex(ValueError, "invalid commit"): + snapshot_from_pages(*args) + + def test_boundaries_and_invalid_requests(self): + snapshot = snapshot_from_pages(4, 1, MIB) + self.assertEqual(require_commit_budget(0, snapshot)["minimum_mib"], 0) + self.assertEqual(require_commit_budget(3, snapshot)["available_mib"], 3) + for invalid in (-1, 1 << 20 | 1, "64", 1.25): + with self.subTest(invalid=invalid), self.assertRaises(ValueError): + require_commit_budget(invalid, snapshot) + + def test_native_layout_and_winapi_arguments(self): + native = NativeGetPerformance() + with patch("host_commit.sys.platform", "win32"), \ + patch("host_commit.C.WinDLL", create=True) as dll: + dll.return_value.GetPerformanceInfo = native + result = read_host_commit() + self.assertEqual(native.seen, [(ctypes.sizeof(PerformanceInformation), + ctypes.sizeof(PerformanceInformation))]) + self.assertEqual(result["limit_mib"], 62) + self.assertEqual(result["used_mib"], 37) + self.assertEqual(result["available_mib"], 25) + self.assertEqual(native.argtypes, [ctypes.POINTER(PerformanceInformation), ctypes.c_uint32]) + dll.assert_called_once_with("psapi.dll", winmode=0x800, use_last_error=True) + + @unittest.skipUnless(sys.platform == "win32", "Windows-only live PSAPI smoke") + def test_native_windows_budget_has_valid_counts(self): + # A harmless real-API smoke: no images or allocations are involved. + budget = read_host_commit() + self.assertGreater(budget["limit_mib"], 0) + self.assertGreaterEqual(budget["used_mib"], 0) + self.assertGreaterEqual(budget["available_mib"], 0) + self.assertLessEqual(budget["available_mib"], budget["limit_mib"]) + self.assertTrue(require_commit_budget(0, budget)["meets_minimum"]) + + def test_winapi_failure_and_unsupported_host(self): + with self.assertRaisesRegex(OSError, "Windows host"): + read_host_commit() + native = NativeGetPerformance(success=False) + with patch("host_commit.sys.platform", "win32"), \ + patch("host_commit.C.WinDLL", create=True) as dll, \ + patch("host_commit.C.get_last_error", create=True, return_value=1455): + dll.return_value.GetPerformanceInfo = native + with self.assertRaisesRegex(OSError, "GetPerformanceInfo failed") as raised: + read_host_commit() + self.assertEqual(raised.exception.errno, 1455) + + def test_cli_fails_before_reading_package_or_loading_guest(self): + with patch("pe_run_package.read_host_commit", return_value=snapshot_from_pages(4, 2, MIB)), \ + patch("pe_run_package.inspect") as inspect, \ + patch("pe_run_package.run") as runner, \ + patch.object(sys, "argv", ["pe_run_package.py", "unused.dll", "missing-directory", + "app.exe", "--min-commit-mib", "3"]), \ + redirect_stderr(io.StringIO()) as errors: + with self.assertRaises(SystemExit) as result: + pe_run_package.main() + self.assertEqual(result.exception.code, 1) + self.assertIn("commit headroom 2 MiB", errors.getvalue()) + inspect.assert_not_called() + runner.assert_not_called() + + def test_successful_preflight_reports_snapshot_only_when_requested(self): + with TemporaryDirectory() as temp: + root = Path(temp) + args = ["pe_run_package.py", str(root / "mapper.dll"), str(root), "app.exe", + "--preflight-only"] + with patch("pe_run_package.inspect", return_value={"entry": "app.exe"}), \ + patch("pe_run_package.run", return_value={"entry_executed": False}) as runner, \ + patch("pe_run_package.read_host_commit", return_value=snapshot_from_pages(9, 2, MIB)) as read: + with patch.object(sys, "argv", [*args, "--min-commit-mib", "7"]), \ + redirect_stdout(io.StringIO()) as out: + pe_run_package.main() + self.assertEqual(json.loads(out.getvalue())["host_commit"], + {"limit_mib": 9, "used_mib": 2, "available_mib": 7, + "minimum_mib": 7, "meets_minimum": True}) + self.assertTrue(runner.call_args.kwargs["preflight_only"]) + with patch.object(sys, "argv", args), redirect_stdout(io.StringIO()) as out: + pe_run_package.main() + self.assertEqual(json.loads(out.getvalue()), {"entry_executed": False}) + read.assert_called_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/host_commit.py b/tools/host_commit.py new file mode 100644 index 000000000..8bdf263d8 --- /dev/null +++ b/tools/host_commit.py @@ -0,0 +1,72 @@ +"""Read the Windows system commit budget before starting a mapped PE package. + +The system commit limit includes RAM and paging-file backing; it is NOT the +amount of free physical RAM. This is a snapshot, not a reservation. +""" + +import ctypes as C +import sys + +MIB = 1 << 20 + + +class PerformanceInformation(C.Structure): + """Windows psapi.h PERFORMANCE_INFORMATION; DWORD is always 32 bits.""" + + _fields_ = [ + ("cb", C.c_uint32), + ("CommitTotal", C.c_size_t), + ("CommitLimit", C.c_size_t), + ("CommitPeak", C.c_size_t), + ("PhysicalTotal", C.c_size_t), + ("PhysicalAvailable", C.c_size_t), + ("SystemCache", C.c_size_t), + ("KernelTotal", C.c_size_t), + ("KernelPaged", C.c_size_t), + ("KernelNonpaged", C.c_size_t), + ("PageSize", C.c_size_t), + ("HandleCount", C.c_uint32), + ("ProcessCount", C.c_uint32), + ("ThreadCount", C.c_uint32), + ] + + +def snapshot_from_pages(limit_pages, used_pages, page_size): + """Pure conversion of GetPerformanceInfo page counts; never wrap under pressure.""" + if not page_size or not limit_pages: + raise ValueError("Windows reported an invalid commit page size or limit") + limit_bytes = int(limit_pages) * int(page_size) + used_bytes = int(used_pages) * int(page_size) + free_bytes = max(limit_bytes - used_bytes, 0) + return {"limit_mib": limit_bytes // MIB, "used_mib": used_bytes // MIB, + "available_mib": free_bytes // MIB, "available_bytes": free_bytes} + + +def read_host_commit(): + """GetPerformanceInfo from System32 psapi.dll; never reads guest image bytes.""" + if sys.platform != "win32": + raise OSError("Windows system commit information requires a Windows host") + info = PerformanceInformation() + info.cb = C.sizeof(PerformanceInformation) + # Only the Windows system copy, never a DLL planted beside the package. + psapi = C.WinDLL("psapi.dll", winmode=0x800, use_last_error=True) + get_performance = psapi.GetPerformanceInfo + get_performance.argtypes = [C.POINTER(PerformanceInformation), C.c_uint32] + get_performance.restype = C.c_int + if not get_performance(C.byref(info), info.cb): + raise OSError(C.get_last_error(), "GetPerformanceInfo failed") + return snapshot_from_pages(info.CommitLimit, info.CommitTotal, info.PageSize) + + +def require_commit_budget(minimum_mib, snapshot): + """Reject a requested budget before any guest module is mapped or started.""" + if not isinstance(minimum_mib, int) or minimum_mib < 0 or minimum_mib > 1 << 20: + raise ValueError("--min-commit-mib must be between 0 and 1048576") + if snapshot["available_bytes"] < minimum_mib * MIB: + raise ValueError( + f"Windows system commit headroom {snapshot['available_mib']} MiB is below the " + f"requested {minimum_mib} MiB. This is commit budget, not free RAM: " + "close other processes or review the Windows paging-file size") + return {"limit_mib": snapshot["limit_mib"], "used_mib": snapshot["used_mib"], + "available_mib": snapshot["available_mib"], "minimum_mib": minimum_mib, + "meets_minimum": True} diff --git a/tools/pe_run_package.py b/tools/pe_run_package.py index 1eb132af6..f948c2b14 100644 --- a/tools/pe_run_package.py +++ b/tools/pe_run_package.py @@ -11,6 +11,7 @@ import sys from pe_package_preflight import inspect +from host_commit import read_host_commit, require_commit_budget # --trap-callable exit codes are TRAP_EXIT_BASE | trap number (1-based, in sorted dll!symbol order). TRAP_EXIT_BASE = 0xE7A00000 @@ -280,6 +281,9 @@ def main(): parser.add_argument("--pin-shim", action="append", default=[], metavar="DLL", help="keep a named external shim loaded until this process exits") parser.add_argument("--system", action="append", default=[], metavar="DLL") + parser.add_argument("--min-commit-mib", type=int, metavar="MIB", + help="optional Windows system commit-headroom check before loading any DLL; " + "0 reports headroom without imposing a minimum") mode = parser.add_mutually_exclusive_group() mode.add_argument("--preflight-only", action="store_true") mode.add_argument("--trap-callable", action="append", default=[], metavar="DLL!SYMBOL", @@ -288,6 +292,13 @@ def main(): f"{TRAP_EXIT_BASE:#x} | trap number; any unlisted unresolved external is still refused") options = parser.parse_args() try: + # Perform the opt-in check before parsing the package or loading providers. + # A successful check does not reserve memory and cannot promise startup. + commit_report = None + if options.min_commit_mib is not None: + if not 0 <= options.min_commit_mib <= 1 << 20: + raise ValueError("--min-commit-mib must be between 0 and 1048576") + commit_report = require_commit_budget(options.min_commit_mib, read_host_commit()) root = options.package.resolve(strict=True) shims = {name.casefold(): Path(path).resolve(strict=True) for name, path in options.shim} system = {name.casefold() for name in options.system} @@ -298,6 +309,8 @@ def main(): preflight_only=options.preflight_only, pin_shims={name.casefold() for name in options.pin_shim}, trap_callable=options.trap_callable) + if commit_report is not None: + result = {**result, "host_commit": commit_report} except (ValueError, OSError) as exc: parser.exit(1, f"{exc}\n") print(json.dumps(result, indent=2)) From d34ee740ad0edbad234e64427b6c0ef59d7272e6 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 19:48:21 +0800 Subject: [PATCH 119/775] shader: lower gfx1030 2D comparison sampling offsets --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 5 + README.md | 1 + docs/experiments.md | 27 +++++ tests/pixel_compare_sample_check.py | 152 ++++++++++++++++++++++++++++ tools/pixel_aot.py | 60 ++++++----- 6 files changed, 222 insertions(+), 24 deletions(-) create mode 100644 tests/pixel_compare_sample_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ca992ab00..f584537ed 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -39,6 +39,7 @@ jobs: python3 -B tests/depth_mask_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/pixel_aot_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/pixel_sample_offset_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 + python3 -B tests/pixel_compare_sample_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/pixel_compare_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/compute_store_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/compute_mimg_msaa_check.py --binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 diff --git a/CMakeLists.txt b/CMakeLists.txt index 7dc782fe7..c353fee9f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6157,6 +6157,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_pack_b32_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_pack_b32_${adapter}.txt") + add_test(NAME pixel_aot_compare_sample_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_compare_sample_check.py" draw "${DXC_EXECUTABLE}" + "$" "${adapter}") + set_tests_properties(pixel_aot_compare_sample_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_compare_sample_${adapter}.txt") add_test(NAME pixel_aot_compare_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_compare_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 1f3967100..c375e4e0e 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 formatted UINT buffer reads | Lower [indexed `buffer_load_format_*` with caller-declared RGBA32 UINT](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-reads) and verify one to four channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_format_'` | | gfx1030 formatted D16 UINT writes | Lower [indexed packed `buffer_store_format_d16_x/xy/xyzw`](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-writes) and verify the untouched halfword and record padding. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | gfx1030 formatted UINT buffer writes | Lower [indexed `buffer_store_format_*` with matching caller-declared UINT texels](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-writes) and compare full UAV readback with a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | +| gfx1030 depth-comparison sampling | Lower [2D comparison samples with and without offsets](docs/experiments.md#gfx1030-2d-comparison-sampling). | `ctest --preset dev --no-tests=error -R '^pixel_aot_compare_sample_' -V` | | gfx1030 pixel sampling offsets | Lower [four 2D sample offset forms](docs/experiments.md#offline-pixel-shader-recompilation) with a known packed XY displacement. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_offset_' -V` | | Shader census | [Distinguish archive records, header digests and cache-index entries](docs/experiments.md#reporting-shader-census-populations) before choosing a coverage denominator. | `ctest --preset dev --no-tests=error -R "^shader_metadata_census$" -V` | | Shader effect metadata | Inventory the [candidate programs for a named SGD5 effect](docs/experiments.md#candidate-programs-for-a-named-sgd5-effect) using independently located archive ranges. | `ctest --preset dev --no-tests=error -R "^sgd5_effect_candidates$" -V` | diff --git a/docs/experiments.md b/docs/experiments.md index 6631ee3ef..d5b488069 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5667,6 +5667,33 @@ With registration, the callers' predicates accept GPU-intended memory and reject | `era_query_registry` | Null, empty and wrapping ranges are refused. Exact, front, back, containing and contained overlaps are refused, adjacent ranges are accepted, and unregistering needs the exact base. | | `era_query_short` | A 47-byte buffer returns 0 with `ERROR_BAD_LENGTH` and is left untouched. A 48-byte buffer succeeds without writing the tail byte. A null output returns `ERROR_BAD_LENGTH` at 47 bytes and `ERROR_NOACCESS` at 48 or 64 bytes, matching desktop `VirtualQueryEx`. | +### gfx1030 2D comparison sampling + +The pixel profile also lowers `image_sample_c`, `image_sample_c_o`, and +`image_sample_c_lz_o` on a 2D R32_FLOAT view with a matching comparison +sampler and `dmask:0x1`. The contiguous address registers contain an optional +packed XY offset, the compare reference, then U and V. The immediate offset +uses the signed six-bit fields and DXIL range documented above. The implicit +forms require whole-quad UVs and source sampler `MIN_LOD = MAX_LOD = 0`. +Bind a desktop maximum LOD of zero or a one-mip view for these forms. +The LOD-zero offset form uses `SampleCmpLevelZero` directly. The accepted +point and bilinear filters, coordinate precision and reference range are +those of the existing comparison sampler profile. + +An independent CPU reference clamps and compares the texture taps before +interpolation. The translated DXIL draw compares every output channel at +8×8 and 16×16 for point and bilinear sampling. The offset mutations replace +`(1, -2)` with `(0, 0)` and must produce a pixel mismatch. LLVM 15 assembles +and disassembles all three gfx1030 encodings and exercises the container CLI. + +```sh +python3 -B tests/pixel_compare_sample_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 +``` + +```powershell +ctest --preset dev --no-tests=error -R '^pixel_aot_compare_sample_(warp|hardware)$' -V +``` + ### Desktop xmem.dll `src/xmem_shim.cpp` builds `xmem.dll`, which exports the four functions the package DLLs import by name. The call shapes come from the observed call sites, not from a published header: diff --git a/tests/pixel_compare_sample_check.py b/tests/pixel_compare_sample_check.py new file mode 100644 index 000000000..0549ae19e --- /dev/null +++ b/tests/pixel_compare_sample_check.py @@ -0,0 +1,152 @@ +"""Exercise gfx1030 2D comparison sampling against an independent CPU image.""" +from fractions import Fraction +import math +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from pixel_compare_check import ( + CONSTANT_REFERENCE, DEPTHS, D3D12_FILTER, TEXTURE, compile_shader, passes, + pixel_aot, prefix, run_case, sampler_moves, sampler_words, tail, texel, translate, +) +from compute_store_check import assemble +from pixel_aot_check import envelope, write_record + +FORMS = ("image_sample_c", "image_sample_c_o", "image_sample_c_lz_o") +OFFSET = (1, -2) + + +def program(op, words, *, packed="0x3e01", quad=True): + lines = prefix() + if quad: + lines = ["s_mov_b64 s[50:51], exec", "s_wqm_b64 exec, exec", *lines, + "s_and_b64 exec, exec, s[50:51]"] + first = 7 + if op.endswith("_o"): + first = 6 + lines.append(f"v_mov_b32_e32 v6, {packed}") + return lines + sampler_moves(words) + [ + "v_mov_b32_e32 v7, s60", + f"{op} v12, v[{first}:9], s[28:35], s[40:43] dmask:0x1 dim:SQ_RSRC_IMG_2D", + ] + tail(reference="v7") + + +def must_reject(function, diagnostic): + try: + function() + except ValueError as error: + assert diagnostic in str(error), str(error) + else: + raise AssertionError(f"Expected rejection containing {diagnostic!r}") + + +def controls(): + words = sampler_words("LESS", "point") + for op in FORMS: + hlsl = translate(program(op, words), words) + method = "SampleCmpLevelZero" if "_lz" in op else "SampleCmp" + assert f"tex.{method}(samp, float2(uv.x, uv.y)," in hlsl + assert (", int2(1, -2))" in hlsl) == op.endswith("_o") + for op in FORMS[:2]: + must_reject(lambda: translate(program(op, words, quad=False), words), "quad provenance") + clamped = sampler_words("LESS", "point", w1=0x100000) + must_reject(lambda: translate(program(op, clamped), clamped), "MAX_LOD 0") + for op in FORMS[1:]: + for packed, reason in (("s61", "known packed integer"), ("0x40", "canonical 2D"), ("8", "[-8, 7]")): + must_reject(lambda: translate(program(op, words, packed=packed), words), reason) + for old, new, reason in ( + ("v[6:9]", "[v6, v8, v9]", "contiguous address"), + ("dmask:0x1", "dmask:0x2", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D a16", "Unsupported instruction"), + ("s_waitcnt vmcnt(0)", "v_add_f32_e32 v12, 0, v12", "Write overlaps an outstanding sample"), + ): + lines = [line.replace(old, new) for line in program(op, words)] + must_reject(lambda: translate(lines, words), reason) + + +def binary(directory, assembler, objcopy, library): + words = sampler_words("LESS", "point") + features = "+wavefrontsize64,-wavefrontsize32" + for op in FORMS: + lines = program(op, words) + code = assemble(directory, assembler, objcopy, lines, cpu="gfx1030", features=features) + decoded = pixel_aot.disassemble(code, library, cpu=b"gfx1030", features=features.encode(), offsets=True) + assert [line for _, line in decoded if line.startswith("image_")] == [ + line for line in lines if line.startswith("image_") + ] + expected = translate(lines, words) + assert translate(decoded, words) == expected + archive = directory / "fixture.bin" + archive.write_bytes(envelope(code)) + output = directory / "fixture.hlsl" + subprocess.run([sys.executable, "-B", pixel_aot.__file__, archive, "fixture", "--llvm", library, + "--cpu", "gfx1030", "--texture-sgpr", "20", "--interp-sgpr", "24", + "--sampler-words", *(hex(word) for word in words), "--constant-descriptor", "0x40", + "--output", output], check=True) + assert output.read_text(encoding="utf-8") == expected + + +def reference(px, py, size, mode, displacement): + # Compare each tap before weighting. The fixture's positions are exact in the + # six-bit fractional coordinate grid and include clamp-to-edge footprints. + u = TEXTURE * Fraction(2 * px + 1, 2 * size) + displacement[0] + v = TEXTURE * Fraction(2 * py + 1, 2 * size) + displacement[1] + if mode == "point": + return float(passes("LESS", CONSTANT_REFERENCE, texel(math.floor(u), math.floor(v)))) + u -= Fraction(1, 2) + v -= Fraction(1, 2) + x, y = math.floor(u), math.floor(v) + fx, fy = u - x, v - y + return float(sum(wx * wy * passes("LESS", CONSTANT_REFERENCE, texel(x + dx, y + dy)) + for dx, wx in ((0, 1 - fx), (1, fx)) for dy, wy in ((0, 1 - fy), (1, fy)))) + + +def write_case(path, size, mode, displacement): + data = bytearray(struct.pack("<6I", D3D12_FILTER[mode], 2, TEXTURE, TEXTURE, size, size)) + data.extend(struct.pack("<64f", CONSTANT_REFERENCE, *([0.0] * 63))) + data.extend(struct.pack(f"<{len(DEPTHS)}f", *DEPTHS)) + for y in range(size): + for x in range(size): + data.extend(struct.pack("<4f", reference(x, y, size, mode, displacement), CONSTANT_REFERENCE, 0.5, 1.0)) + path.write_bytes(data) + + +def draw(directory, compiler, renderer, adapter): + for op in FORMS: + displacement = OFFSET if op.endswith("_o") else (0, 0) + for mode in ("point", "bilinear"): + words = sampler_words("LESS", mode) + for mutant in (False, True): + if mutant and not op.endswith("_o"): + continue + source = directory / f"{op}-{mode}-{mutant}.hlsl" + shader = source.with_suffix(".cso") + source.write_text(translate(program(op, words, packed="0" if mutant else "0x3e01"), words), + encoding="ascii") + compile_shader(compiler, source, shader) + for size in (8, 16): + case = source.with_suffix(".case") + write_case(case, size, mode, displacement) + result = run_case(renderer, adapter, shader, case) + if result == 77: + raise SystemExit(77) + if mutant: + assert result.returncode == 1 and "pixel_mismatch" in result.stderr, (result.stdout, result.stderr) + print(f"{op} {mode} size={size} zero offset: {result.stderr.strip().splitlines()[0]}") + else: + assert result.returncode == 0, (result.stdout, result.stderr) + print(result.stdout, end="") + write_record(os.environ.get("FORM_COVERAGE_RECORD")) + + +if __name__ == "__main__": + controls() + if len(sys.argv) > 1: + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="compare-sample-", dir=out) as directory: + {"binary": binary, "draw": draw}[sys.argv[1]](Path(directory), *sys.argv[2:]) + print("Three gfx1030 2D comparison sample forms checked") diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 4330b3e8b..9f7310ed8 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -228,6 +228,23 @@ def disassemble(code, library, *, cpu=b"gfx1013", offsets=False, features=b""): COMPARISON_FILTERS = {0: ("point", 0x80), 1: ("bilinear", 0x94)} +def sample_offset_arg(reg, vector, sample_dest, known_ssa_bits): + if reg in sample_dest: + raise ValueError("Sample offset used before vmcnt wait") + value = vector.get(reg) + if not isinstance(value, str) or value not in known_ssa_bits: + raise ValueError("Sample offset must be a known packed integer word") + packed = known_ssa_bits[value] + # RDNA 2 packs signed six-bit X and Y at bits [5:0] and [13:8]. + if packed & ~0x3f3f: + raise ValueError("Sample offset must be a canonical 2D offset word") + x = ((packed & 0x3f) ^ 0x20) - 0x20 + y = (((packed >> 8) & 0x3f) ^ 0x20) - 0x20 + if not (-8 <= x <= 7 and -8 <= y <= 7): + raise ValueError("Sample offset is outside the DXIL immediate range [-8, 7]") + return f", int2({x}, {y})" + + def comparison_sampler_state(words): """Decode the sampler descriptor fields that change an image_sample_c_lz result on a 2D texture. @@ -3990,22 +4007,7 @@ def match(pattern): coord_regs = [f"v{n}" for n in coords] offset_arg = "" if has_offset: - offset_reg = coord_regs.pop(0) - if offset_reg in sample_dest: - raise ValueError("Sample offset used before vmcnt wait") - value = vector.get(offset_reg) - if not isinstance(value, str) or value not in known_ssa_bits: - raise ValueError("Sample offset must be a known packed integer word") - packed = known_ssa_bits[value] - # RDNA 2 packs signed six-bit X and Y at bits [5:0] and [13:8]. - # Require a canonical 2D word and offsets representable in ps_6_0. - if packed & ~0x3f3f: - raise ValueError("Sample offset must be a canonical 2D offset word") - x = ((packed & 0x3f) ^ 0x20) - 0x20 - y = (((packed >> 8) & 0x3f) ^ 0x20) - 0x20 - if not (-8 <= x <= 7 and -8 <= y <= 7): - raise ValueError("Sample offset is outside the DXIL immediate range [-8, 7]") - offset_arg = f", int2({x}, {y})" + offset_arg = sample_offset_arg(coord_regs.pop(0), vector, sample_dest, known_ssa_bits) if any(reg not in vector for reg in coord_regs): raise ValueError("Unsupported texture coordinate") @@ -4087,14 +4089,18 @@ def sample_coord(reg): vector_loads += 1 vector[dst] = f"alu{i}" sample_dest[dst] = vector_loads - elif m := match(r"image_sample_c_lz (v\d+), (?:v\[(\d+):(\d+)\]|\[(v\d+), (v\d+), (v\d+)\]), " + elif m := match(r"(image_sample_c(?:_lz)?(?:_o)?) (v\d+), (?:v\[(\d+):(\d+)\]|\[(v\d+), (v\d+), (v\d+)\]), " r"s\[(\d+):(\d+)\], s\[(\d+):(\d+)\] dmask:0x1 dim:SQ_RSRC_IMG_2D"): - # Depth comparison at LOD zero. The RDNA2 address order puts the reference before the - # coordinates, so the operands are (reference, u, v), in one VGPR range or the NSA form. - dst, first, last, *nsa = m.groups()[:6] - image = registers(*m.groups()[6:8], 8) - state = registers(*m.groups()[8:10], 4) - address = ([f"v{n}" for n in registers(first, last, 3)] if first is not None else nsa) + # The optional packed offset precedes the reference, followed by the UV pair. + op, dst, first, last, *nsa = m.groups()[:7] + image = registers(*m.groups()[7:9], 8) + state = registers(*m.groups()[9:11], 4) + has_offset = op.endswith("_o") + explicit_zero = op.removesuffix("_o") == "image_sample_c_lz" + if first is None and op != "image_sample_c_lz": + raise ValueError("Comparison sample requires a contiguous address") + address = ([f"v{n}" for n in registers(first, last, 3 + has_offset)] + if first is not None else nsa) if any(int(reg[1:]) > 255 for reg in (dst, *address)): raise ValueError("Comparison sample VGPR out of range") if sampler is None or second_texture_offset is not None or sample_kind == "plain": @@ -4106,6 +4112,11 @@ def sample_coord(reg): or descriptor != [("tex", j) for j in range(8)] or [scalar.get(f"s{n}") for n in state] != list(sampler)): raise ValueError("Unsupported image or sampler binding") + if not explicit_zero and sampler[1] & 0xfff000: + raise ValueError("Implicit comparison sampling requires MAX_LOD 0") + offset_arg = sample_offset_arg(address.pop(0), vector, sample_dest, known_ssa_bits) if has_offset else "" + if not explicit_zero and any(vector.get(reg) not in quad_values for reg in address[1:]): + raise ValueError("Implicit comparison sampling requires coordinates with quad provenance") if sample_kind is None: lines[lines.index(SAMPLED_RESOURCES)] = comparison_resources(comparison_sampler_state(sampler)) sample_kind = "comparison" @@ -4117,7 +4128,8 @@ def sample_coord(reg): if not isinstance(value, str) or not (value in quad_values or value.startswith(("sample", "alu", "params"))): raise ValueError("Unsupported comparison sample operand") reference, u, v = values - lines.append(f" float sample{i} = tex.SampleCmpLevelZero(samp, float2({u}, {v}), {reference});") + method = "SampleCmpLevelZero" if explicit_zero else "SampleCmp" + lines.append(f" float sample{i} = tex.{method}(samp, float2({u}, {v}), {reference}{offset_arg});") samples += 1 vector_loads += 1 vector[dst] = f"sample{i}" From 0468663422ef91cb3c82dc06819eb4325f0281cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 15:43:19 +0300 Subject: [PATCH 120/775] startup: check the slice footprint plan and re-read rules src/startup_stubs/slice_footprints.h decides which NV12 descriptions the XG stand-in accepts, how often the draw uploader reads a CPU-backed texture again, what it asks GetCopyableFootprints for, and how many bytes each placed subresource spans. It was reached only through the GPU draws. startup_nv12_draw passes one accepted 8x4 NV12 image and refuses an array, and startup_plane_refresh checks the re-read intervals of one R8 plane and one RGBA8 texture. A supports() that dropped the odd-size, zero-size, mip or sample condition, a re-read rule that dropped the mip or layer condition or made the 32 MiB cap exclusive, a constructor that refused 15 mips or called through a null device, and a bytes() that counted a full row pitch for the last row all left every CPU and WARP test that reaches the header passing. startup_slice_footprints builds against the header alone, with a stand-in device that answers only GetCopyableFootprints. It refuses twelve NV12 descriptions, each with one field changed, checks the re-read intervals and the cap at exactly and one byte past 32 MiB, the footprint request for NV12, 15, 16 and 0 mips and without a device, and the bytes of six hand-worked footprints up to 4 GiB. Each of those mutants now fails it. The padded-last-row control expects a full last row and must fail. --- CMakeLists.txt | 9 + docs/startup-runtime.md | 6 + tests/startup_slice_footprints_check.cpp | 228 +++++++++++++++++++++++ 3 files changed, 243 insertions(+) create mode 100644 tests/startup_slice_footprints_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 360629d97..e31a0f50c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -500,6 +500,15 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_nv12_draw_${backend} PROPERTIES ENVIRONMENT "X2W_SHIM_DRAW_ADAPTER=${backend}" TIMEOUT 60 SKIP_RETURN_CODE 77) endforeach() +# The same header without a GPU (src/startup_stubs/slice_footprints.h): accepted NV12 descriptions, +# re-read intervals and size cap, the footprint request and the bytes up to the end of the last row. +# The mutated run is the negative control. +add_executable(startup_slice_footprints_check tests/startup_slice_footprints_check.cpp) +target_include_directories(startup_slice_footprints_check PRIVATE src) +target_compile_features(startup_slice_footprints_check PRIVATE cxx_std_17) +add_test(NAME startup_slice_footprints COMMAND startup_slice_footprints_check) +add_test(NAME startup_slice_footprints_padded_control COMMAND startup_slice_footprints_check --mutate padded-last-row) +set_tests_properties(startup_slice_footprints_padded_control PROPERTIES WILL_FAIL TRUE) find_program(DXC_EXECUTABLE dxc REQUIRED) get_filename_component(DXC_BIN_DIR "${DXC_EXECUTABLE}" DIRECTORY) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c8a81a8b3..2ffc8c332 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -555,6 +555,12 @@ cmake --build --preset release --target startup_nv12_draw d3d12_xs_shim ctest --preset release --no-tests=error -R '^startup_nv12_draw_' -V ``` +`ctest --preset dev --no-tests=error -R '^startup_slice_footprints' -V` checks +`src/startup_stubs/slice_footprints.h` without a GPU. It covers NV12 descriptions refused for odd or zero +sizes, mips, layers, samples or dimension; the one-frame R8 plane and 15-frame re-read intervals and the +inclusive 32 MiB cap; the footprint request for 15 and 16 mips and without a device; and the bytes up to +the end of the last row. The padded-last-row control must fail. + ## Host processors without the console's instructions A console executable is built for one processor. On a host that lacks CLWB, CLZERO, MONITORX, diff --git a/tests/startup_slice_footprints_check.cpp b/tests/startup_slice_footprints_check.cpp new file mode 100644 index 000000000..4ab9a4102 --- /dev/null +++ b/tests/startup_slice_footprints_check.cpp @@ -0,0 +1,228 @@ +// Checks src/startup_stubs/slice_footprints.h without a GPU: which descriptions the XG stand-in +// accepts, when a CPU-backed texture is read again, what the constructor asks GetCopyableFootprints +// for, and the bytes one placed subresource spans. +#include "startup_stubs/slice_footprints.h" + +#include +#include +#include +#include +#include +#include + +namespace { +using x2w_startup::SliceFootprints; +int failures, cases; +bool padded_control; + +void expect(bool ok, const char* name) +{ + ++cases; + if (!ok) { + std::printf("FAIL %s\n", name); + ++failures; + } +} + +D3D12_RESOURCE_DESC texture(DXGI_FORMAT format, UINT64 width, UINT height, UINT16 layers = 1, UINT16 mips = 1) +{ + return {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, layers, mips, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; +} + +// A stand-in device. A COM object starts with a pointer to its method table, and slot 38 is +// GetCopyableFootprints in the declaration order of ID3D12DeviceVtbl in d3d12.h. Every other slot +// ends the run, so a call to another method fails. +constexpr std::size_t slots = 64, footprints_slot = 38; + +template +void unexpected_slot() +{ + std::printf("FAIL unexpected call to method slot %zu\n", N); + std::fflush(stdout); + std::_Exit(1); +} + +template +std::array trap_table(std::index_sequence) +{ + return {reinterpret_cast(&unexpected_slot)...}; +} + +struct FootprintCall { + int calls; + D3D12_RESOURCE_DESC desc; + UINT first, count; + UINT64 base; + const void *layouts, *rows, *row_bytes, *total; +}; +FootprintCall footprint_call; + +void STDMETHODCALLTYPE fake_footprints(ID3D12Device*, const D3D12_RESOURCE_DESC* desc, UINT first, UINT count, UINT64 base, + D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts, UINT* rows, UINT64* row_bytes, UINT64* total) +{ + footprint_call = {footprint_call.calls + 1, *desc, first, count, base, layouts, rows, row_bytes, total}; + for (UINT i = 0; i < count; ++i) { + layouts[i] = {0x1000u * i, {desc->Format, 100 + i, 50 + i, 1, 256}}; + rows[i] = 50 + i; + row_bytes[i] = 100 + i; + } + *total = 0x12345; +} + +struct FakeObject { + const void* const* table; +}; + +bool same(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) +{ + return a.Dimension == b.Dimension && a.Alignment == b.Alignment && a.Width == b.Width && a.Height == b.Height && + a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format && + a.SampleDesc.Count == b.SampleDesc.Count && a.SampleDesc.Quality == b.SampleDesc.Quality && a.Layout == b.Layout && + a.Flags == b.Flags; +} + +// Construct a plan through the fake device: either one request for every plane of every mip, from +// subresource 0 at offset 0 into the plan's own arrays, or no request and no size. +void constructed(const char* name, ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, UINT mips, UINT planes, bool requested) +{ + footprint_call = {}; + const SliceFootprints plan(device, desc, mips); + ++cases; + const UINT count = mips * planes; + const bool ok = plan.planes == planes && plan.count == count && + (requested ? footprint_call.calls == 1 && footprint_call.first == 0 && footprint_call.count == count && + footprint_call.base == 0 && same(footprint_call.desc, desc) && + footprint_call.layouts == plan.placed && footprint_call.rows == plan.rows && + footprint_call.row_bytes == plan.row_bytes && footprint_call.total == &plan.size && + plan.size == 0x12345 && plan.placed[count - 1].Offset == 0x1000u * (count - 1) && + plan.rows[count - 1] == 50 + count - 1 + : footprint_call.calls == 0 && plan.size == UINT64_MAX); + if (!ok) { + std::printf("FAIL %s: planes %u count %u size 0x%llx, device asked %d times for %u from %u at %llu (expected %u, %u, %s)\n", + name, plan.planes, plan.count, static_cast(plan.size), footprint_call.calls, + footprint_call.count, footprint_call.first, static_cast(footprint_call.base), planes, + count, requested ? "asked once" : "not asked"); + ++failures; + } +} + +// The bytes from the first byte of a placed subresource to the end of its last row, set up +// without a device: RowPitch * (Depth * rows - 1) + row_bytes. The control expects a full row pitch +// for the last row as well. +void spans(const char* name, UINT index, UINT pitch, UINT depth, UINT rows, UINT64 row_bytes, UINT64 last_row_end, + UINT64 last_pitch_end) +{ + const UINT64 expected = padded_control ? last_pitch_end : last_row_end; + SliceFootprints plan(nullptr, texture(DXGI_FORMAT_R8_UNORM, 1, 1), 1); + plan.placed[index].Footprint = {DXGI_FORMAT_R8_UNORM, 1, rows, depth, pitch}; + plan.rows[index] = rows; + plan.row_bytes[index] = row_bytes; + ++cases; + if (plan.bytes(index) != expected) { + std::printf("FAIL %s: %llu bytes, expected %llu\n", name, static_cast(plan.bytes(index)), + static_cast(expected)); + ++failures; + } +} +} // namespace + +int main(int argc, char** argv) +{ + // --mutate padded-last-row: the expectations of a bytes() that counts a full row pitch for the + // last row (a negative control: the check must then fail). + padded_control = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "padded-last-row") == 0; + if (argc > 1 && !padded_control) { + std::printf("unknown mutation\n"); + return 2; + } + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); + + // supports(): any format other than NV12, and NV12 only as one even-sized 2D image. + D3D12_RESOURCE_DESC volume = texture(DXGI_FORMAT_R8G8B8A8_UNORM, 7, 5, 3, 3); + volume.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + volume.SampleDesc.Count = 4; + expect(SliceFootprints::supports(volume), "supports an odd 3D RGBA8 volume with mips and samples"); + expect(SliceFootprints::supports(texture(DXGI_FORMAT_R8_UNORM, 17, 3, 6, 5)), "supports an odd R8 array with mips"); + expect(SliceFootprints::supports(texture(DXGI_FORMAT_NV12, 8, 4)), "supports NV12 8x4"); + expect(SliceFootprints::supports(texture(DXGI_FORMAT_NV12, 2, 2)), "supports NV12 2x2"); + expect(SliceFootprints::supports(texture(DXGI_FORMAT_NV12, 3840, 2160)), "supports NV12 3840x2160"); + const D3D12_RESOURCE_DESC nv12 = texture(DXGI_FORMAT_NV12, 8, 4); + struct Named { + const char* name; + D3D12_RESOURCE_DESC desc; + } refused[] = {{"NV12 width 7", nv12}, {"NV12 height 3", nv12}, {"NV12 width 0", nv12}, {"NV12 height 0", nv12}, + {"NV12 2 mips", nv12}, {"NV12 0 mips", nv12}, {"NV12 2 layers", nv12}, {"NV12 0 layers", nv12}, + {"NV12 2 samples", nv12}, {"NV12 3D", nv12}, {"NV12 1D", nv12}, {"NV12 buffer", nv12}}; + refused[0].desc.Width = 7; + refused[1].desc.Height = 3; + refused[2].desc.Width = 0; + refused[3].desc.Height = 0; + refused[4].desc.MipLevels = 2; + refused[5].desc.MipLevels = 0; + refused[6].desc.DepthOrArraySize = 2; + refused[7].desc.DepthOrArraySize = 0; + refused[8].desc.SampleDesc.Count = 2; + refused[9].desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + refused[10].desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; + refused[11].desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + for (const auto& item : refused) expect(!SliceFootprints::supports(item.desc), item.name); + + // recheck_cpu_texture(): a single R8 plane after one frame, anything else after 15, never past 32 MiB. + constexpr UINT64 cap = 32ull << 20; + const D3D12_RESOURCE_DESC r8 = texture(DXGI_FORMAT_R8_UNORM, 1920, 1080); + const D3D12_RESOURCE_DESC rgba = texture(DXGI_FORMAT_R8G8B8A8_UNORM, 1920, 1080); + expect(!x2w_startup::recheck_cpu_texture(r8, 4096, 0), "R8 plane: not in the same frame"); + expect(x2w_startup::recheck_cpu_texture(r8, 4096, 1), "R8 plane: after one frame"); + expect(x2w_startup::recheck_cpu_texture(r8, cap, 1), "R8 plane: exactly 32 MiB"); + expect(!x2w_startup::recheck_cpu_texture(r8, cap + 1, 1), "R8 plane: one byte past 32 MiB"); + expect(!x2w_startup::recheck_cpu_texture(r8, cap + 1, 1000), "R8 plane: past 32 MiB, 1000 frames"); + const Named others[] = {{"R8 with 2 mips", texture(DXGI_FORMAT_R8_UNORM, 1920, 1080, 1, 2)}, + {"R8 array of 2", texture(DXGI_FORMAT_R8_UNORM, 1920, 1080, 2, 1)}, + {"R8G8", texture(DXGI_FORMAT_R8G8_UNORM, 960, 540)}, {"RGBA8", rgba}}; + for (const auto& other : others) + for (const UINT frames : {1u, 14u, 15u}) { + char name[64]; + std::snprintf(name, sizeof(name), "%s: %s after %u frames", other.name, frames == 15 ? "read" : "not read", frames); + expect(x2w_startup::recheck_cpu_texture(other.desc, 4096, frames) == (frames == 15), name); + } + expect(x2w_startup::recheck_cpu_texture(rgba, cap, 15), "RGBA8: exactly 32 MiB"); + expect(!x2w_startup::recheck_cpu_texture(rgba, cap + 1, 15), "RGBA8: one byte past 32 MiB"); + + // The constructor asks for every plane of every mip, from subresource 0 at offset 0, into its + // own arrays, and asks nothing for a description or mip count it cannot hold. + const auto device_table = [] { + auto table = trap_table(std::make_index_sequence{}); + table[footprints_slot] = reinterpret_cast(&fake_footprints); + return table; + }(); + FakeObject device_object{device_table.data()}; + auto* device = reinterpret_cast(&device_object); + constructed("NV12 8x4", device, nv12, 1, 2, true); + constructed("R8 17x3", device, texture(DXGI_FORMAT_R8_UNORM, 17, 3), 1, 1, true); + constructed("RGBA8 16384x16384, 15 mips", device, texture(DXGI_FORMAT_R8G8B8A8_UNORM, 16384, 16384, 1, 15), 15, 1, true); + constructed("RGBA8 array of 6, 3 mips", device, texture(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 64, 6, 3), 3, 1, true); + constructed("RGBA8, 16 mips", device, texture(DXGI_FORMAT_R8G8B8A8_UNORM, 32768, 32768, 1, 16), 16, 1, false); + constructed("RGBA8, 0 mips", device, texture(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 64), 0, 1, false); + constructed("NV12 width 7", device, refused[0].desc, 1, 2, false); + constructed("NV12 2 layers", device, refused[6].desc, 1, 2, false); + // XG builds a plan before it checks for a device; a plan that calls through null ends the run here. + std::printf("plan without a device\n"); + std::fflush(stdout); + constructed("NV12 8x4 without a device", nullptr, nv12, 1, 2, false); + + // bytes(): the last row ends after its row bytes, not after a full row pitch. + spans("R8 17x3, pitch 256", 0, 256, 1, 3, 17, 529, 768); + spans("one row of 64 bytes, pitch 256", 0, 256, 1, 1, 64, 64, 256); + spans("NV12 chroma (index 1), 4x2 R8G8, pitch 256", 1, 256, 1, 2, 8, 264, 512); + spans("last index (29), 3 rows of 40 bytes, pitch 512", SliceFootprints::max_mips * 2 - 1, 512, 1, 3, 40, 1064, 1536); + spans("4 slices of 2 rows of 320 bytes, pitch 512", 0, 512, 4, 2, 320, 3904, 4096); + spans("16384 rows of 256 KiB (4 GiB)", 0, 262144, 1, 16384, 262144, 0x100000000ull, 0x100000000ull); + + if (failures) { + std::printf("startup_slice_footprints: %d of %d FAILED\n", failures, cases); + return 1; + } + std::printf("startup_slice_footprints: PASS (%d cases)\n", cases); + return 0; +} From 974b3888ee2c3e92496e3027397e819dd7ee59ec Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:43:42 +0800 Subject: [PATCH 121/775] docs: record the virtual-memory device cases on Intel Xe2 The vm_translation paragraph records the device, sequence, range and lifetime cases per adapter. Add the Intel Arc 140T at 06e2ff78: 44 GPU virtual address bits per resource and 48 per process, both device cases passing with the reserve-only and interior-address refusals at 0x80070057, and the 64 KiB shift control missing all 1,024 intended words. Docs only. --- docs/experiments.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 5407b0597..456c4c868 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6117,6 +6117,8 @@ A static read of the main executable shows that, after device creation, it keeps On Windows 10 19045 with D3D12 10.0.19041.7291, both device cases passed on in-box WARP 10.0.19041.7811 and on an RTX 3080 Ti (driver 32.0.16.1047). The second placed buffer's address following `B + offset` is observed on these adapters; D3D12 does not document it for placed resources. Both sequence cases passed on the same adapters, in-box WARP 10.0.19041.7811 reporting 32 GPU virtual address bits per resource and 47 per process, and the RTX 3080 Ti 40 and 40. The range case passed on the RTX 3080 Ti (eight 4 GiB windows) and on WARP 1.0.22 loaded app-locally. On in-box WARP 10.0.19041.7811 (nine 4095 MiB windows), `range_warp` skips at the capability check. The lifetime and partial-failure cases passed on both adapters. With the range open, the released device kept 8 references on the RTX and 9 on in-box WARP. +On Windows 11 build 26300.9974, the Intel Arc 140T (device `7d51`, driver 32.0.101.8132) reported 44 GPU virtual address bits per resource and 48 per process, and passed both device cases: a reserve-only range and an address inside the allocation both returned `0x80070057`, and shifting `B` by one 64 KiB page missed the intended destination in all 1,024 words. + Because reserve-only ranges and addresses inside an allocation cannot be opened, the committed-heap layout of the device cases needs all of A committed and wrapped once. A 16 or 24 GiB range would be committed in full, and separately opened pieces would each get their own GPU base. The range uses reserved buffers instead, filled by copy. Neither the CPU range A nor the title's device is connected to it yet. Run `ctest --preset dev --no-tests=error -R '^vm_translation_' -V`. From d05eb21a2fcce8f6e666fc4ebf24b575cd06e8a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 15:39:27 +0300 Subject: [PATCH 122/775] startup: check the stand-in switch and trap-log contract src/startup_stubs/local_log.h holds the switch reader and line logger that the audio, input, runtime-proxy, XG and xmem stand-ins share. No test includes it directly. Single-point mutants were run against the 24 non-hardware tests that load those DLLs (startup_stubs, the xmem_shim group, startup_acphal_apu_free, startup_heartbeat_commit and the startup_xg_bc* checks). Only two failed them: a switch that is on for any non-empty value (startup_xg_bc7_layout sets X2W_D3D12_RENDER=0) and a log opened with truncation (startup_stubs counts trap lines). Nine survived: env_on or logf losing the caller's last error, LF-only lines, an off-by-one or missing truncation clamp, no stderr write, no trap-log append, a too-strict MAX_PATH check and an off-by-one in first_calls. startup_local_log includes the header and points its own stderr handle and X2W_TRAP_LOG at files in a fresh folder under %TEMP%. It checks which switch values are on, the last error after env_on and logf, the exact stderr and log bytes for two appended lines and an existing log, lines at, one past and far past the 1,533-byte limit, log paths of MAX_PATH - 1 characters and longer, an unopenable log, and first_calls. Each of the eleven mutants above now fails it. Dropping the length < MAX_PATH check still passes: on Windows build 26300 a buffer too small for the value comes back with an empty string, so that path opens nothing. --- CMakeLists.txt | 6 ++ docs/startup-runtime.md | 7 ++ tests/startup_local_log_check.cpp | 162 ++++++++++++++++++++++++++++++ 3 files changed, 175 insertions(+) create mode 100644 tests/startup_local_log_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 360629d97..9337d51a0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -411,6 +411,12 @@ endforeach() set_tests_properties(xmem_page_runs_device_hardware PROPERTIES SKIP_RETURN_CODE 77) add_executable(startup_launch_probe tests/startup_launch_probe.cpp) target_compile_features(startup_launch_probe PRIVATE cxx_std_17) +# Switch values, the kept last error and the stderr and X2W_TRAP_LOG lines of the logging every +# permissive stand-in shares (src/startup_stubs/local_log.h). +add_executable(startup_local_log_check tests/startup_local_log_check.cpp) +target_include_directories(startup_local_log_check PRIVATE src) +target_compile_features(startup_local_log_check PRIVATE cxx_std_17) +add_test(NAME startup_local_log COMMAND startup_local_log_check) # Input for the startup debugger's diagnostics check (tests/startup_debug_check.py). add_executable(startup_debug_probe tests/startup_debug_probe.cpp) target_compile_features(startup_debug_probe PRIVATE cxx_std_17) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c8a81a8b3..1910d2852 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -231,6 +231,13 @@ ctest --preset release --no-tests=error -R '^startup_inflate$' -V | `X2W_VALLOC_MIN=` | the startup debugger logs each virtual-memory allocation of at least that size to `files.txt` (`VALLOC`), with the requested address (0 for any, unreadable for an incomplete read), size, type, protection and the main-image and stand-in return addresses on the caller's stack | | `X2W_HOST_CPU=1` (`run.ps1 -HostCpu`) | the startup debugger rewrites main-image instructions the host processor lacks at their first fault: see [Host processors without the console's instructions](#host-processors-without-the-consoles-instructions) | +The stand-ins share one switch reader and line logger (`src/startup_stubs/local_log.h`): a value +that starts with `1` is on; `0`, an empty value and another first character are off. Neither changes +the caller's last error, and each line ends in CRLF on stderr and is appended to `X2W_TRAP_LOG`. +`ctest --preset dev --no-tests=error -R '^startup_local_log$' -V` checks those switch values, the kept +last error and the exact bytes on stderr and in the log, including a line cut to 1,533 bytes, an +existing log that keeps its contents and log paths at and past `MAX_PATH`. + The startup shader cache key includes the translator revision. After updating from an earlier translation revision, run the recording build once to emit requests, run `python tools/startup/gfx2hlsl.py --pending `, diff --git a/tests/startup_local_log_check.cpp b/tests/startup_local_log_check.cpp new file mode 100644 index 000000000..828befe71 --- /dev/null +++ b/tests/startup_local_log_check.cpp @@ -0,0 +1,162 @@ +// Checks src/startup_stubs/local_log.h, the switches and log lines every permissive stand-in shares: +// which switch values count as on, the caller's last error kept by env_on and logf, and the exact +// bytes logf writes to stderr and appends to %X2W_TRAP_LOG%. The check points its own stderr handle +// and X2W_TRAP_LOG at files in a fresh folder under %TEMP% and removes them at the end. +#include "startup_stubs/local_log.h" + +#include +#include +#include +#include + +namespace { +constexpr DWORD sentinel = 0x2A5A0BADu; // an error value no call in the header sets +constexpr std::size_t longest = 1536 - 3; // the line buffer, less CRLF and the terminator +int failures; + +void check(bool condition, const char* what) +{ + if (condition) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +std::string read_file(const std::wstring& path) +{ + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +void write_file(const std::wstring& path, const std::string& text) +{ + std::ofstream(path, std::ios::binary | std::ios::trunc) << text; +} + +void same_bytes(const std::string& got, const std::string& expected, const char* what) +{ + if (got == expected) return; + std::size_t at = 0; + while (at < got.size() && at < expected.size() && got[at] == expected[at]) ++at; + std::printf("FAIL: %s: %zu bytes, expected %zu; first difference at byte %zu\n", what, got.size(), expected.size(), + at); + ++failures; +} + +// value nullptr: the variable is absent. +void switch_value(const char* value, bool on, const char* what) +{ + SetEnvironmentVariableA("X2W_LOCAL_LOG_SWITCH", value); + SetLastError(sentinel); + const bool got = x2w_local::env_on("X2W_LOCAL_LOG_SWITCH"); + const DWORD error = GetLastError(); + if (got != on || error != sentinel) { + std::printf("FAIL: switch %s: %s with last error %lu, expected %s with %lu\n", what, got ? "on" : "off", error, + on ? "on" : "off", sentinel); + ++failures; + } +} + +void logged(const char* text, const char* what) +{ + SetLastError(sentinel); + x2w_local::logf("%s", text); + if (GetLastError() != sentinel) { + std::printf("FAIL: %s: last error %lu after logf, expected %lu\n", what, GetLastError(), sentinel); + ++failures; + } +} +} // namespace + +int main() +{ + wchar_t temp[MAX_PATH]; + const DWORD temp_length = GetTempPathW(MAX_PATH, temp); + if (!temp_length || temp_length >= MAX_PATH) return std::printf("FAIL: no temporary folder\n"), 2; + const std::wstring dir = std::wstring(temp) + L"x2w_local_log_" + std::to_wstring(GetCurrentProcessId()); + if (!CreateDirectoryW(dir.c_str(), nullptr)) return std::printf("FAIL: cannot create the work folder\n"), 2; + const std::wstring err_path = dir + L"\\stderr.txt", log_path = dir + L"\\trap.log"; + // The longest path that fits MAX_PATH with its terminator (259 characters), and one character more. + const std::size_t name_length = MAX_PATH - 1 - dir.size() - 1; + if (name_length < 5 || name_length > 250) return std::printf("FAIL: unusable temporary folder length\n"), 2; + const std::wstring fit_path = dir + L"\\" + std::wstring(name_length - 4, L'f') + L".log"; + const std::wstring long_path = dir + L"\\" + std::wstring(name_length - 3, L'g') + L".log"; + + // Switches: a value that starts with '1' is on, anything else is off. env_on leaves the caller's last + // error alone either way. Values of four or more characters are not checked: they do not fit the + // reader's 4-byte buffer, and whether that is intended is not settled. + switch_value(nullptr, false, "absent"); + switch_value("", false, "empty"); + for (const char* on : {"1", "10", "1x", "100"}) switch_value(on, true, on); + for (const char* off : {"0", "2", "01", " 1", "on", "yes"}) switch_value(off, false, off); + SetEnvironmentVariableA("X2W_LOCAL_LOG_SWITCH", nullptr); + + // logf writes to whatever the stderr handle is when it runs. + HANDLE saved_err = GetStdHandle(STD_ERROR_HANDLE); + HANDLE err = CreateFileW(err_path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (err == INVALID_HANDLE_VALUE) return std::printf("FAIL: cannot create %ls\n", err_path.c_str()), 2; + SetStdHandle(STD_ERROR_HANDLE, err); + + // Two lines append to a log that already holds a line; a missing variable leaves the log alone. + std::string expected_err; + write_file(log_path, "earlier line\r\n"); + SetEnvironmentVariableA("X2W_TRAP_LOG", nullptr); + logged("not in the log", "no X2W_TRAP_LOG"); + expected_err += "not in the log\r\n"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + logged("first line", "existing log"); + SetLastError(sentinel); + x2w_local::logf("second %s %d 0x%x", "line", -7, 0xBEEFu); + check(GetLastError() == sentinel, "last error after a formatted logf"); + expected_err += "first line\r\nsecond line -7 0xbeef\r\n"; + std::string expected_log = "earlier line\r\nfirst line\r\nsecond line -7 0xbeef\r\n"; + same_bytes(read_file(log_path), expected_log, "log after two lines"); + + // Truncation: the longest line fits whole, longer ones keep their first 1533 bytes and still end in CRLF. + const std::string text(longest + 400, 'L'); + for (const std::size_t length : {longest - 1, longest, longest + 1, text.size()}) { + logged(text.substr(0, length).c_str(), "long line"); + const std::string line = text.substr(0, length < longest ? length : longest) + "\r\n"; + expected_err += line; + expected_log += line; + } + same_bytes(read_file(log_path), expected_log, "log after long lines"); + + // A log path of exactly MAX_PATH - 1 characters is used; one character more is ignored, even right after + // a line that went to another log (the buffer a too-long value leaves is undefined). + SetEnvironmentVariableW(L"X2W_TRAP_LOG", fit_path.c_str()); + logged("longest log path", "longest log path"); + expected_err += "longest log path\r\n"; + same_bytes(read_file(fit_path), "longest log path\r\n", "log at the longest path"); + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + logged("before a long path", "short log path"); + expected_err += "before a long path\r\n"; + expected_log += "before a long path\r\n"; + SetEnvironmentVariableW(L"X2W_TRAP_LOG", long_path.c_str()); + logged("path too long", "log path too long"); + expected_err += "path too long\r\n"; + same_bytes(read_file(log_path), expected_log, "log after a path past MAX_PATH"); + check(GetFileAttributesW(long_path.substr(0, MAX_PATH - 1).c_str()) == INVALID_FILE_ATTRIBUTES, + "no file at the truncated long path"); + + // A log that cannot be opened (a folder) leaves the last error alone too. + SetEnvironmentVariableW(L"X2W_TRAP_LOG", dir.c_str()); + logged("log is a folder", "log is a folder"); + expected_err += "log is a folder\r\n"; + SetEnvironmentVariableA("X2W_TRAP_LOG", nullptr); + + SetStdHandle(STD_ERROR_HANDLE, saved_err); + CloseHandle(err); + same_bytes(read_file(err_path), expected_err, "stderr"); + + // first_calls: true for exactly the first limit calls. + LONG counter = 0; + int allowed = 0; + for (int i = 0; i < 5; ++i) allowed += x2w_local::first_calls(counter, 3); + check(allowed == 3, "first_calls allows 3 of 5 calls with limit 3"); + + for (const std::wstring& path : {err_path, log_path, fit_path}) DeleteFileW(path.c_str()); + check(RemoveDirectoryW(dir.c_str()) != FALSE, "the work folder holds only the expected files"); + std::printf(failures ? "startup_local_log: %d failure(s)\n" : "startup_local_log: ok\n", failures); + return failures ? 1 : 0; +} From 0b47a18a6fca6eb6699eafef7a14b356f8c76d53 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 20:43:45 +0800 Subject: [PATCH 123/775] Bound exported slots and HRESULT encodings --- tests/startup_triage_run_check.py | 4 +++- tools/startup/triage_run.py | 17 ++++++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 08eadd753..685737466 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -107,6 +107,8 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: x2w-dstorage entry type 3 failed: AcmeTitle bad [secret](https://acme.example/leak) x2w-dstorage Factory::OpenFile path="x" riid={1} -> fail acme_widget_7f3a x2w-runtime 0000018012345678::slot9(0x1) -> 0x80004005 from +0x1 +x2w-runtime 0000018012345678::slot5555555555555555(0x1) -> 0x80004005 +x2w-runtime 0000018012345678::slot9(0x1) -> 0x00000180DEADBEEF """ PRIVATE_SHADER_FAILS = [ "AcmeModule: 0000018012345678 acme_widget_7f3a [secret](https://acme.example/leak)", @@ -118,7 +120,7 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: ] PRIVATE_NEEDLES = [ "Acme", "acme", "ACME", "Private", "secret", "leak", "widget", "7f3a", "exploded", - "0000018012345678", "12345678", "[", "](", "http", ".dll", "Opaque", + "0000018012345678", "12345678", "5555555555555555", "deadbeef", "[", "](", "http", ".dll", "Opaque", ] diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index da52649df..d1e3f6074 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -47,8 +47,9 @@ } TRAP_TAGS = {"x2w-trap", "x2w-noop", "x2w-continue", "x2w-fail"} OTHER = "other (text omitted)" -RE_DEC = re.compile(r"\d{1,10}\Z") +RE_DEC = re.compile(r"[0-9]{1,10}\Z") RE_HEX = re.compile(r"0x[0-9a-fA-F]{1,8}\Z") +RE_SIGN_EXTENDED_HRESULT = re.compile(r"0xffffffff([89a-f][0-9a-f]{7})\Z", re.IGNORECASE) RE_SLOT = re.compile(r"(?:[A-Za-z0-9_]+!)?(?:([A-Za-z0-9_]+)::)?slot(\d{1,4})\b") RE_OPENFILE_FAIL = re.compile(r"fail(?: \(err (\d{1,10})\))?\Z") MNEMONIC_FAMILY = r"(v|s|ds|buffer|tbuffer|image|flat|global|scratch|exp|lds)_[a-z0-9_]{1,40}" @@ -96,9 +97,9 @@ def classify_shader_reason(line: str) -> str: RE_TRAP_TAG = re.compile(r'^(x2w-(?:trap|noop|continue|fail))\s+(\S+)') RE_D3D12_PIPELINE_TRAP = re.compile( - r'x2w-d3d12\s+Device::slot(\d+)\((Create(?:Graphics|Compute)PipelineState)\)' + r'x2w-d3d12\s+Device::slot([0-9]{1,4})\((Create(?:Graphics|Compute)PipelineState)\)' ) -RE_D3D12_IID_PASS = re.compile(r'x2w-d3d12\s+Device::slot(\d+)\s+passes an IID:') +RE_D3D12_IID_PASS = re.compile(r'x2w-d3d12\s+Device::slot([0-9]{1,4})\s+passes an IID:') RE_D3D12_VIEW_SKIPPED = re.compile(r'x2w-d3d12\s+Device::slot(\d+)\s+view skipped:\s+(.+)$') RE_D3D12_FORWARDED_RESULT = re.compile(r'::slot\d+\(.*\)\s*->\s*(0x[0-9a-fA-F]+)\s*$') RE_D3D12_SLOT_CALL = re.compile(r'x2w-d3d12\s+([A-Za-z0-9_]+::slot\d+)\b') @@ -121,7 +122,7 @@ def classify_shader_reason(line: str) -> str: ) RE_RUNTIME_CALL = re.compile( - r'x2w-(?:runtime|api)\s+[0-9a-fA-F]+::slot(\d+)(?:\([^)]*\))?\s+->\s+(0x[0-9a-fA-F]+)' + r'x2w-(?:runtime|api)\s+[0-9a-fA-F]+::slot([0-9]{1,4})(?:\([^)]*\))?\s+->\s+(0x[0-9a-fA-F]+)' ) RE_RUNTIME_STORAGE = re.compile( r'x2w-runtime\s+persistent local storage:\s+local object instead of\s+(0x[0-9a-fA-F]+)' @@ -148,7 +149,13 @@ def _parse_kv_block(block: str) -> dict[str, str]: def _is_failed_hresult(hex_text: str) -> tuple[bool, str]: - val = int(hex_text, 16) & 0xFFFFFFFF + extended = RE_SIGN_EXTENDED_HRESULT.fullmatch(hex_text) + if extended: + val = int(extended.group(1), 16) + elif RE_HEX.fullmatch(hex_text): + val = int(hex_text, 16) + else: + return False, "?" return (val & 0x80000000) != 0, f"0x{val:08x}" From d3ddcf0c0ba1f44bf2535a564436c7c084d003be Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:45:23 +0800 Subject: [PATCH 124/775] docs: record the queue-ordered and raw view cases on Intel Xe2 The tile-remap subsection describes vm_copy_queue, vm_page_provenance, vm_raw_srv and vm_raw_uav without an adapter result. Record the Intel Arc 140T run at 06e2ff78 with the fixture's own counters: 16,384 of 16,384 remapped words differing for the early read, 0 of 1,024 for each provenance case, 0 cross-page and 0 shifted SRV mismatches with a 1,024 word negative control, and a UAV swap that keeps 5 of 5 intended words while refusing 11 stores. Docs only. --- docs/experiments.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 6631ee3ef..a0f252cb8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6146,6 +6146,8 @@ Run `cmake --build --preset dev --target vm_copy_queue_check` and `ctest --prese Run `cmake --build --preset dev --target vm_copy_queue_check` and `ctest --preset dev --no-tests=error -R '^vm_raw_uav_' -V`. +On Windows 11 build 26300.9974, the Intel Arc 140T (device `7d51`, driver 32.0.101.8132) reproduced these numbers in the four cases above: the deliberately early read differed from all 16,384 remapped words while both ordered reads matched, `vm_page_provenance` reported 0 of 1,024 mismatches in each of its three cases, `vm_raw_srv` reported 0 cross-page and 0 shifted mismatches with its negative control at 1,024 of 1,024, and `vm_raw_uav` changed 5 of 2,048 words with 5 of 5 intended words kept when the two windows were swapped and refused 11 stores. + #### Xbox frame events and token wait semantics (#874) The source-built frame events fixture (`tests/cpu/frame_events_caller.asm`, `tests/cpu/frame_events_provider.cpp`, `tests/cpu/frame_events_check.py`, CTest `cpu_native_frame_events`) models the scheduling and wait semantics of the Xbox frame-pacing extensions in `d3d12_xs.dll`: From e706f7312ab22f2eb035ecce024ed8e42e13f868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 15:48:57 +0300 Subject: [PATCH 125/775] runtime: check the device creation IID inventory src/d3d12x_device_slots.cpp decides which IIDs D3D12XboxCreateDevice accepts and prints the GUID text of a refused one. The device fixtures request only IID_ID3D12Device and the fixture GUID {7c0e1a10-5f2d-4b7a-9a51-3d9c6b2e8f01}, and vm_translation_device asks for ID3D12Device3, so no test asks for ID3D12Device1, a near neighbor of ID3D12Device or the null IID. Single-point mutants (a GUID comparison that ignores the last Data4 byte or Data3, ID3D12Device1 accepted as documented, find_creation_iid matching the GUID{} vtable rows, a corrupted ID3D12Device1 row) all left the 26 WARP and device-free d3d12x_, d3d12_xs_shim_, vm_translation_ and startup device tests passing. Uppercase or swapped Data2/Data3 text and a corrupted ID3D12Device row were already caught. d3d12x_device_slots compiles the inventory without a device and checks the rows and acceptance for the SDK __uuidof values of ID3D12Device, ID3D12Device1 and ID3D12Device3, every IID one byte away from ID3D12Device, the null IID and IUnknown, and format_iid against hand-written lowercase text. Each of those mutants now fails it. The device1 control expects ID3D12Device1 to be accepted and must fail. --- CMakeLists.txt | 8 +++ docs/experiments.md | 7 +++ tests/d3d12x_device_slots_check.cpp | 87 +++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+) create mode 100644 tests/d3d12x_device_slots_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c68580f9b..e79ca224f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -198,6 +198,14 @@ set_target_properties(d3d12_xs_shim PROPERTIES OUTPUT_NAME d3d12_xs) target_include_directories(d3d12_xs_shim PRIVATE src) target_compile_features(d3d12_xs_shim PRIVATE cxx_std_17) target_link_libraries(d3d12_xs_shim PRIVATE d3d12) +# The creation-IID gate and refusal text of D3D12XboxCreateDevice (src/d3d12x_device_slots.h), +# without a device. The mutated run is the negative control. +add_executable(d3d12x_device_slots_check tests/d3d12x_device_slots_check.cpp src/d3d12x_device_slots.cpp) +target_include_directories(d3d12x_device_slots_check PRIVATE src) +target_compile_features(d3d12x_device_slots_check PRIVATE cxx_std_17) +add_test(NAME d3d12x_device_slots COMMAND d3d12x_device_slots_check) +add_test(NAME d3d12x_device_slots_device1_control COMMAND d3d12x_device_slots_check --mutate device1) +set_tests_properties(d3d12x_device_slots_device1_control PROPERTIES WILL_FAIL TRUE) # Fixture-only desktop xgameruntime.dll. The single X-macro table in # xgameruntime_shim.cpp distinguishes implemented synchronous contracts from diff --git a/docs/experiments.md b/docs/experiments.md index 5407b0597..dcc16aaff 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5787,6 +5787,13 @@ It also keeps a non-null parameter block at `E_INVALIDARG`. Run `ctest --preset dev --no-tests=error -R '^d3d12x_device_' -V`. +Those device fixtures request only `IID_ID3D12Device` and the fixture GUID, so +`ctest --preset dev --no-tests=error -R '^d3d12x_device_slots' -V` checks the inventory without a +device. It checks the rows and acceptance for the Windows SDK `__uuidof` values of `ID3D12Device`, +`ID3D12Device1` and `ID3D12Device3`, refuses every IID one byte away from `ID3D12Device` and the +null IID of the vtable rows, and compares `format_iid` with hand-written lowercase text. The +`d3d12x_device_slots_device1_control` run expects `ID3D12Device1` to be accepted and must fail. + The struct-return adapter compares the two candidate addresses with the live device supplied by the fixture. A vtable match alone is ambiguous because the first word of the stack buffer can also contain that vtable address. The fixture supplies the two explicit pointer orders and forwards diff --git a/tests/d3d12x_device_slots_check.cpp b/tests/d3d12x_device_slots_check.cpp new file mode 100644 index 000000000..168d8e7bf --- /dev/null +++ b/tests/d3d12x_device_slots_check.cpp @@ -0,0 +1,87 @@ +// Checks src/d3d12x_device_slots.h without a device: which creation IIDs D3D12XboxCreateDevice +// accepts, the inventory row each IID resolves to, and the GUID text its refusal prints. Expected +// IIDs come from the Windows SDK through __uuidof and the expected text is written out by hand. +#include "d3d12x_device_slots.h" + +#include +#include + +namespace { +namespace slots = d3d12x_device_slots; +int failures; + +void row(const char* label, REFIID iid, const char* name, slots::SlotState state, bool accepted) +{ + const slots::Entry* entry = slots::find_creation_iid(iid); + if (!entry || entry->kind != slots::SlotKind::creation_iid || std::strcmp(entry->name, name) != 0 || + entry->state != state || entry->index != slots::no_vtable_index) { + std::printf("FAIL %s: expected the %s creation row\n", label, name); + ++failures; + } + if (slots::accepts_creation_iid(iid) != accepted) { + std::printf("FAIL %s: accepted=%d, expected %d\n", label, !accepted, accepted); + ++failures; + } +} + +void absent(const char* label, REFIID iid) +{ + if (slots::find_creation_iid(iid) || slots::accepts_creation_iid(iid)) { + std::printf("FAIL %s: found or accepted an IID outside the inventory\n", label); + ++failures; + } +} + +void text(const char* label, REFIID iid, const char* expected) +{ + const slots::IidText got = slots::format_iid(iid); + if (got[slots::iid_text_size - 1] != '\0' || std::strcmp(got.data(), expected) != 0) { + std::printf("FAIL %s: \"%.*s\", expected \"%s\"\n", label, static_cast(got.size()), got.data(), + expected); + ++failures; + } +} +} // namespace + +int main(int argc, char** argv) +{ + // --mutate device1 expects ID3D12Device1 to be accepted (a negative control: the check must fail). + const bool device1_control = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && + std::strcmp(argv[2], "device1") == 0; + if (argc > 1 && !device1_control) { + std::fputs("usage: d3d12x_device_slots_check [--mutate device1]\n", stderr); + return 2; + } + + const GUID device = __uuidof(ID3D12Device); + row("ID3D12Device", device, "ID3D12Device", slots::SlotState::implemented, true); + row("ID3D12Device1", __uuidof(ID3D12Device1), "ID3D12Device1", slots::SlotState::documented_unimplemented, + device1_control); + row("ID3D12Device3", __uuidof(ID3D12Device3), "ID3D12Device3", slots::SlotState::observed_unimplemented, + false); + + // Every IID one byte away from the accepted one is outside the inventory. + for (std::size_t byte = 0; byte < sizeof(GUID); ++byte) { + GUID neighbor = device; + reinterpret_cast(&neighbor)[byte] ^= 0x01; + char label[48]; + std::snprintf(label, sizeof(label), "ID3D12Device with byte %zu changed", byte); + absent(label, neighbor); + } + // The vtable rows carry GUID{}; a null IID must not resolve to one of them. + absent("null IID", GUID{}); + absent("IUnknown", __uuidof(IUnknown)); + + text("ID3D12Device text", device, "{189819f1-1db6-4b57-be54-1821339b85f7}"); + text("ID3D12Device1 text", __uuidof(ID3D12Device1), "{77acce80-638e-4e65-8895-c1f23386863e}"); + text("ID3D12Device3 text", __uuidof(ID3D12Device3), "{81dadc15-2bad-4392-93c5-101345c4aa98}"); + text("null IID text", GUID{}, "{00000000-0000-0000-0000-000000000000}"); + text("all-ones IID text", GUID{0xffffffff, 0xffff, 0xffff, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, + "{ffffffff-ffff-ffff-ffff-ffffffffffff}"); + text("field order text", GUID{0x01234567, 0x89ab, 0xcdef, {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}}, + "{01234567-89ab-cdef-0123-456789abcdef}"); + + if (failures) return 1; + std::printf("d3d12x device slots: creation IIDs, neighbors and text exact\n"); + return 0; +} From db7d106ddbf6af26b6c47e8895630129bef29710 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:49:41 +0100 Subject: [PATCH 126/775] startup_stubs/inflate: fix fixed_block static-init data race --- src/startup_stubs/inflate.h | 37 +++++++++++++++----------- tests/startup_inflate_status.cpp | 45 ++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 15 deletions(-) diff --git a/src/startup_stubs/inflate.h b/src/startup_stubs/inflate.h index a43302c35..e17be1e13 100644 --- a/src/startup_stubs/inflate.h +++ b/src/startup_stubs/inflate.h @@ -132,23 +132,30 @@ inline bool stored(Stream& s) noexcept return true; } +struct FixedTables { + Huffman lencode; + Huffman distcode; +}; + +inline FixedTables make_fixed_tables() noexcept +{ + FixedTables tables{}; + std::uint8_t lengths[288]; + int i = 0; + for (; i < 144; ++i) lengths[i] = 8; + for (; i < 256; ++i) lengths[i] = 9; + for (; i < 280; ++i) lengths[i] = 7; + for (; i < 288; ++i) lengths[i] = 8; + construct(tables.lencode, lengths, 288); + for (i = 0; i < 30; ++i) lengths[i] = 5; + construct(tables.distcode, lengths, 30); + return tables; +} + inline bool fixed_block(Stream& s) noexcept { - static Huffman lencode, distcode; - static bool ready = false; - if (!ready) { - std::uint8_t lengths[288]; - int i = 0; - for (; i < 144; ++i) lengths[i] = 8; - for (; i < 256; ++i) lengths[i] = 9; - for (; i < 280; ++i) lengths[i] = 7; - for (; i < 288; ++i) lengths[i] = 8; - construct(lencode, lengths, 288); - for (i = 0; i < 30; ++i) lengths[i] = 5; - construct(distcode, lengths, 30); - ready = true; - } - return codes(s, lencode, distcode); + static const FixedTables tables = make_fixed_tables(); + return codes(s, tables.lencode, tables.distcode); } inline bool dynamic_block(Stream& s) noexcept diff --git a/tests/startup_inflate_status.cpp b/tests/startup_inflate_status.cpp index bf807e5b7..ecd7840ba 100644 --- a/tests/startup_inflate_status.cpp +++ b/tests/startup_inflate_status.cpp @@ -1,9 +1,11 @@ #include "startup_stubs/inflate.h" #include +#include #include #include #include +#include #include namespace { @@ -91,6 +93,45 @@ std::vector dynamic_payload() return data; } +bool check_fixed_multithreaded(const std::uint8_t* stream, std::size_t stream_size, const std::uint8_t* expected, + std::size_t expected_size) +{ + constexpr int thread_count = 8; + std::atomic ready_count{0}; + std::atomic go{false}; + std::array thread_ok{}; + std::vector workers; + workers.reserve(thread_count); + + for (int t = 0; t < thread_count; ++t) { + workers.emplace_back([&, t]() { + std::vector out(expected_size, 0xAA); + std::size_t out_size = 999; + ready_count.fetch_add(1, std::memory_order_release); + while (!go.load(std::memory_order_acquire)) std::this_thread::yield(); + const InflateStatus status = inflate_zlib_ex(stream, stream_size, out.data(), out.size(), out_size); + thread_ok[static_cast(t)] = + (status == InflateStatus::ok && out_size == expected_size && + std::memcmp(out.data(), expected, expected_size) == 0) + ? 1 + : 0; + }); + } + + while (ready_count.load(std::memory_order_acquire) < thread_count) std::this_thread::yield(); + go.store(true, std::memory_order_release); + + for (auto& w : workers) w.join(); + + for (int t = 0; t < thread_count; ++t) { + if (!thread_ok[static_cast(t)]) { + std::fprintf(stderr, "fixed_lit_multithreaded: thread %d failed\n", t); + return false; + } + } + return true; +} + } // namespace int main() @@ -158,6 +199,10 @@ int main() bool ok = true; + // Multi-threaded fixed Huffman stress test (run before single-threaded fixed_block calls) + ok = ok && check_fixed_multithreaded(fixed_lit_stream, sizeof(fixed_lit_stream), fixed_lit_expected, + sizeof(fixed_lit_expected)); + // Exact-size buffer -> ok ok = ok && check_ok("stored", stored_stream, sizeof(stored_stream), stored_expected, sizeof(stored_expected)); ok = ok && check_ok("fixed_lit", fixed_lit_stream, sizeof(fixed_lit_stream), fixed_lit_expected, From b9b60f6bb0b6af0173faa014333486732ec7a937 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:50:21 +0100 Subject: [PATCH 127/775] startup: keep shadow-only descriptor table entries in the capture summary describe() paired shadow and token ids with zip(), so a table with no token half listed no entries. Use zip_longest and add regression checks. --- tests/startup_capture_check.py | 25 ++++++++++++++++++++++++- tools/startup/capture.py | 3 ++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/tests/startup_capture_check.py b/tests/startup_capture_check.py index 11cfbd65b..781b92a92 100644 --- a/tests/startup_capture_check.py +++ b/tests/startup_capture_check.py @@ -129,6 +129,29 @@ def check_describe(): assert 'present frame 4 surface Resource@123456' in text +def describe_text(*tables): + data = b''.join([CALL, res(), view(0, 18, RES_W), view(1, 17, 0, b'')] + list(tables)) + out = io.StringIO() + C.describe(load(data), out) + return out.getvalue() + + +def check_describe_shadow_only(): + # A table that carries only the shadow ids (no token half) still lists its entries. + text = describe_text(table(5, 36, 2, 2, 0x3000, HEAP_W, 1, ids=(1, 2))) + assert 'table param 2 heap index 1: 2 of 2 entries known' in text + assert 'SRV view 0 res=123456 dim3 64x32x1' in text and 'CBV view 1 res=0' in text + assert 'token' not in text and 'shadow' not in text + + +def check_describe_one_sided_ids(): + # Zero in one half means "not recorded there"; the entry is still listed from the other half. + text = describe_text(table(5, 36, 2, 2, 0x3000, HEAP_W, 1, ids=(0, 2, 1, 0))) + assert 'table param 2 heap index 1: 2 of 2 entries known' in text + assert 'SRV view 0 (shadow -1 token 0) res=123456' in text + assert 'CBV view 1 (shadow 1 token -1) res=0' in text + + def check_damaged_files(): for cut, words in ((len(FILE) - 3, ('PRES', 'truncated')), # body or header cut short (len(FILE) - 12, ('PRES', 'truncated'))): @@ -155,6 +178,6 @@ def check_mutated_record(): if __name__ == '__main__': - for check in (check_records, check_memory, check_describe, check_damaged_files, check_mutated_record): + for check in (check_records, check_memory, check_describe, check_describe_shadow_only, check_describe_one_sided_ids, check_damaged_files, check_mutated_record): check() print('ok', check.__name__) diff --git a/tools/startup/capture.py b/tools/startup/capture.py index f9df3d205..b51d8fc91 100644 --- a/tools/startup/capture.py +++ b/tools/startup/capture.py @@ -1,4 +1,5 @@ """Reader for capture.bin written by the frame capture (startup tools; see docs/startup-runtime.md).""" +import itertools import struct import sys from collections import defaultdict, Counter @@ -166,7 +167,7 @@ def describe(cap, out=sys.stdout): w('%4d f%d L%03x %-30s %s | %s\n' % (c['seq'], c['frame'], c['list'] & 0xfff, LIST_SLOTS.get(c['slot'], 'slot%d' % c['slot']), ', '.join(args), ' '.join('0x%x' % a for a in c['args'][3:5]))) for t in cap.tables.get(c['seq'], ()): - used = [(i, s, k) for i, (s, k) in enumerate(zip(t['shadow'], t['tokens'])) if s or k] + used = [(i, s, k) for i, (s, k) in enumerate(itertools.zip_longest(t['shadow'], t['tokens'], fillvalue=0)) if s or k] w(' table param %d heap index %d: %d of %d entries known\n' % (t['parameter'] if t['parameter'] != 0xffffffff else -1, t['index'], len(used), t['entries'])) for i, s, k in used[:64]: From 96bef2c186bd86f438211c2415ce1a9a266c81b9 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:50:41 +0100 Subject: [PATCH 128/775] startup_stubs: guard window presenter surface and close state --- docs/startup-runtime.md | 4 + src/startup_stubs/d3d12_present.inl | 24 +++--- src/startup_stubs/present_view_format.h | 8 ++ tests/startup_present_view_check.cpp | 106 +++++++++++++++++++++++- 4 files changed, 131 insertions(+), 11 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a042aa048..3178da59f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -30,6 +30,10 @@ records. The control expects the first blend patch to win and must fail. ## Output window and fallback diagnostics The desktop swap chain has its own top-level window, class `X2WOutputWindow`. +The presenter only samples single-sample 2D surfaces without +`D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE` and with a supported view format +(`src/startup_stubs/present_view_format.h`), and marks itself failed if +closing its command list fails. When a present cannot show its surface, the GDI fallback selects a visible, unowned guest window in the same process. If only the presenter is visible, the fallback leaves it alone. To exercise both z-orders with source-built diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 8eb6afd3e..9b5547280 100644 --- a/src/startup_stubs/d3d12_present.inl +++ b/src/startup_stubs/d3d12_present.inl @@ -107,7 +107,7 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) } if (SUCCEEDED(hr)) hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&p.allocator)); if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, p.allocator, nullptr, IID_PPV_ARGS(&p.list)); - if (SUCCEEDED(hr)) p.list->Close(); + if (SUCCEEDED(hr)) hr = p.list->Close(); if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&p.fence)); p.reached = CreateEventW(nullptr, FALSE, FALSE, nullptr); static const char source[] = @@ -162,22 +162,23 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) { WindowPresenter& p = window_presenter; - if (p.failed) return false; + if (p.failed || !queue || !surface) return false; + const D3D12_RESOURCE_DESC desc = surface->GetDesc(); + if (!x2w_startup::present_surface_supported(desc)) { + static LONG refused; + if (first_calls(refused, 4)) + log("x2w-present surface dim=%d samples=%u flags=0x%x format=%d not supported (present_view_format.h)", + desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); + return false; + } HWND window = output_window(); if (!window) return false; if (!p.chain && !create_window_presenter(queue, window)) { p.failed = true; return false; } - const D3D12_RESOURCE_DESC desc = surface->GetDesc(); - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1) return false; ID3D12Device* device = device_of(the_device); const DXGI_FORMAT view_format = x2w_startup::present_view_format(desc.Format); - if (view_format == DXGI_FORMAT_UNKNOWN) { - static LONG refused; - if (first_calls(refused, 4)) log("x2w-present surface format %d has no single typed view; not shown (present_view_format.h)", desc.Format); - return false; - } D3D12_SHADER_RESOURCE_VIEW_DESC view{}; view.Format = view_format; view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; @@ -202,7 +203,10 @@ bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) p.list->DrawInstanced(3, 1, 0, 0); transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); transition(p.list, surface, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); - if (FAILED(p.list->Close())) return false; + if (FAILED(p.list->Close())) { + p.failed = true; + return false; + } ID3D12CommandList* lists[] = {p.list}; queue->ExecuteCommandLists(1, lists); const HRESULT hr = p.chain->Present(0, 0); diff --git a/src/startup_stubs/present_view_format.h b/src/startup_stubs/present_view_format.h index 17ef9b0e7..fc96f33aa 100644 --- a/src/startup_stubs/present_view_format.h +++ b/src/startup_stubs/present_view_format.h @@ -41,4 +41,12 @@ inline DXGI_FORMAT present_view_format(DXGI_FORMAT format) default: return format; } } + +inline bool present_surface_supported(const D3D12_RESOURCE_DESC& desc) +{ + return desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + desc.SampleDesc.Count == 1 && + (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == 0 && + present_view_format(desc.Format) != DXGI_FORMAT_UNKNOWN; +} } // namespace x2w_startup diff --git a/tests/startup_present_view_check.cpp b/tests/startup_present_view_check.cpp index 38f2f0996..8c3c474fc 100644 --- a/tests/startup_present_view_check.cpp +++ b/tests/startup_present_view_check.cpp @@ -52,6 +52,64 @@ void table() expect("unknown refused", DXGI_FORMAT_UNKNOWN, none); } +void expect_supported(const char* name, const D3D12_RESOURCE_DESC& desc, bool wanted) +{ + const bool got = x2w_startup::present_surface_supported(desc); + if (got != wanted) { + std::printf("FAIL %s: supported=%d, expected %d (dim=%d samples=%u flags=0x%x fmt=%d)\n", + name, got ? 1 : 0, wanted ? 1 : 0, desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); + ++failures; + } +} + +void surface_support() +{ + D3D12_RESOURCE_DESC tex2d{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 16, 16, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + expect_supported("2d rgba8 unorm", tex2d, true); + + D3D12_RESOURCE_DESC rt = tex2d; + rt.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS; + rt.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + expect_supported("2d typeless rt", rt, true); + + D3D12_RESOURCE_DESC deny = tex2d; + deny.Flags = D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; + expect_supported("2d deny_srv", deny, false); + + D3D12_RESOURCE_DESC dsv = tex2d; + dsv.Format = DXGI_FORMAT_D32_FLOAT; + dsv.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; + expect_supported("2d dsv deny_srv", dsv, false); + + D3D12_RESOURCE_DESC buf{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + expect_supported("buffer refused", buf, false); + + D3D12_RESOURCE_DESC tex1d = tex2d; + tex1d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; + tex1d.Height = 1; + expect_supported("1d refused", tex1d, false); + + D3D12_RESOURCE_DESC tex3d = tex2d; + tex3d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + expect_supported("3d refused", tex3d, false); + + D3D12_RESOURCE_DESC msaa = tex2d; + msaa.SampleDesc.Count = 4; + expect_supported("msaa4 refused", msaa, false); + + D3D12_RESOURCE_DESC zero_samples = tex2d; + zero_samples.SampleDesc.Count = 0; + expect_supported("samples0 refused", zero_samples, false); + + D3D12_RESOURCE_DESC unknown_fmt = tex2d; + unknown_fmt.Format = DXGI_FORMAT_UNKNOWN; + expect_supported("unknown fmt refused", unknown_fmt, false); + + D3D12_RESOURCE_DESC ambig_fmt = tex2d; + ambig_fmt.Format = DXGI_FORMAT_R32_TYPELESS; + expect_supported("ambiguous fmt refused", ambig_fmt, false); +} + void check(HRESULT hr, const char* what) { if (FAILED(hr)) throw std::runtime_error(std::string(what) + " failed"); @@ -185,6 +243,50 @@ bool readback(ID3D12Device* device, const Case& item) return bad == 0; } +void verify_surface_guards(ID3D12Device* device) +{ + D3D12_HEAP_PROPERTIES defaults{}; + defaults.Type = D3D12_HEAP_TYPE_DEFAULT; + + const auto create = [&](const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, const char* label) { + ComPtr resource; + check(device->CreateCommittedResource(&defaults, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&resource)), label); + return resource; + }; + + const D3D12_RESOURCE_DESC dsv_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 16, 16, 1, 1, DXGI_FORMAT_D32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE}; + auto dsv = create(dsv_desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, "dsv deny_srv"); + expect_supported("warp dsv deny_srv", dsv->GetDesc(), false); + + const D3D12_RESOURCE_DESC buf_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 64, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + auto buf = create(buf_desc, D3D12_RESOURCE_STATE_COMMON, "buffer"); + expect_supported("warp buffer", buf->GetDesc(), false); + + const D3D12_RESOURCE_DESC msaa_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 16, 16, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {4, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + auto msaa = create(msaa_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, "msaa4"); + expect_supported("warp msaa4", msaa->GetDesc(), false); + + const D3D12_RESOURCE_DESC rt_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 16, 16, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + auto rt = create(rt_desc, D3D12_RESOURCE_STATE_COMMON, "valid rt"); + const D3D12_RESOURCE_DESC actual_rt = rt->GetDesc(); + expect_supported("warp valid rt", actual_rt, true); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr heap; + check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "guard srv heap"); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = x2w_startup::present_view_format(actual_rt.Format); + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + device->CreateShaderResourceView(rt.Get(), &srv, heap->GetCPUDescriptorHandleForHeapStart()); + check(device->GetDeviceRemovedReason(), "device removed reason"); +} + ComPtr create_device(bool warp) { ComPtr factory; @@ -220,11 +322,12 @@ int main(int argc, char** argv) } if (!adapter) { table(); + surface_support(); if (failures) { std::printf("startup_present_view: %d FAILED\n", failures); return 1; } - std::printf("startup_present_view: PASS (4 mapped, 6 typed, 18 refused, 2 invalid)\n"); + std::printf("startup_present_view: PASS (4 mapped, 6 typed, 18 refused, 2 invalid, 11 surface checks)\n"); return 0; } try { @@ -247,6 +350,7 @@ int main(int argc, char** argv) run.view = map_format(item.typeless); if (!readback(device.Get(), run)) ++failures; } + verify_surface_guards(device.Get()); } catch (const std::exception& error) { std::printf("startup_present_view: %s\n", error.what()); return 1; From ac0b5c8a5a1e363ef6c8dfaedc16ac581441d4ee Mon Sep 17 00:00:00 2001 From: Simsalabim <83839581+SimSalabimse@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:56:50 +0100 Subject: [PATCH 129/775] runtime: answer store method 3 with an offline context XStoreCreateContext for the local user writes one context handle instead of E_FAIL. A mutated provider still fails, covered by startup_stubs. Refs #1147 --- CMakeLists.txt | 2 ++ docs/startup-runtime.md | 8 ++++- src/startup_stubs/api_trace.h | 1 + src/startup_stubs/runtime_proxy.cpp | 55 ++++++++++++++++++++++++++++- tests/startup_stub_check.py | 10 ++++++ tests/startup_stub_consumer.cpp | 3 ++ 6 files changed, 77 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d86494067..40416c433 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -342,6 +342,8 @@ target_compile_features(startup_inflate_status PRIVATE cxx_std_17) target_include_directories(startup_inflate_status PRIVATE src) add_test(NAME startup_inflate_status COMMAND startup_inflate_status) target_compile_features(startup_stub_consumer PRIVATE cxx_std_17) +target_include_directories(startup_stub_consumer PRIVATE src) +target_sources(startup_stub_consumer PRIVATE src/startup_stubs/runtime_proxy.cpp) target_link_libraries(startup_stub_consumer PRIVATE startup_stub_chad startup_stub_xg_xs xmem_shim d3d12_xs_shim) # APU heap stand-in: ApuFree reuse, coalescing, refused requests and concurrent callers (docs/startup-runtime.md). add_executable(startup_acphal_apu_free tests/startup_acphal_apu_free.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a042aa048..422c0e624 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -241,7 +241,7 @@ ctest --preset release --no-tests=error -R '^startup_inflate$' -V | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. | | `X2W_AUDIO_PERMISSIVE=1` | audio HAL / APU stand-ins accept their calls (no output) | | `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call | -| `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user | +| `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_STORAGE_PATH`, `X2W_STORAGE_MB`, `X2W_TITLE_ID` | persistent local storage and the manifest values the runtime would return. The path is handed to the executable with a trailing separator, added when missing, because the executable appends names to it as it is; up to 258 characters, a longer value is refused with a log line and `S:\` is used (`src/startup_stubs/storage_root.h`, `ctest --preset release --no-tests=error -R '^startup_storage_root'`) | | `X2W_INPUT_SCRIPT=mask@sec,...` | timed virtual gamepad presses (0x4 = A); keyboard and XInput pad 0 also work | | `X2W_SAMPLER_HEAP=1` | `gfx2hlsl.py` translates a sampler-heap load with a run-time offset into `SamplerState qh[2048] : register(s0, space1)` and writes `smpheap 2048 1 fallback 2047`. The stand-in uses entries 0 to 2046 for the bound heap and reserves entry 2047 for unaligned or out-of-range offsets. It also accepts the original `smpheap 2048 1` manifest with all 2,048 entries available. [#1143](https://github.com/R0Y00/Xbox2Windows/issues/1143) | @@ -253,6 +253,12 @@ ctest --preset release --no-tests=error -R '^startup_inflate$' -V | `X2W_VALLOC_MIN=` | the startup debugger logs each virtual-memory allocation of at least that size to `files.txt` (`VALLOC`), with the requested address (0 for any, unreadable for an incomplete read), size, type, protection and the main-image and stand-in return addresses on the caller's stack | | `X2W_HOST_CPU=1` (`run.ps1 -HostCpu`) | the startup debugger rewrites main-image instructions the host processor lacks at their first fault: see [Host processors without the console's instructions](#host-processors-without-the-consoles-instructions) | +With `X2W_RUNTIME_PROXY=1` and `X2W_FAKE_USER=1`, store-interface method 3 +(`XStoreCreateContext` on provider `0dd112ac`) writes one context handle for the local user and +returns success. Other store methods are not answered: a call that still carries the local user +handle returns `0x80004005`. +[#1147](https://github.com/R0Y00/Xbox2Windows/issues/1147) + The startup shader cache key includes the translator revision. After updating from an earlier translation revision, run the recording build once to emit requests, run `python tools/startup/gfx2hlsl.py --pending `, diff --git a/src/startup_stubs/api_trace.h b/src/startup_stubs/api_trace.h index eb29198ad..c99311bf2 100644 --- a/src/startup_stubs/api_trace.h +++ b/src/startup_stubs/api_trace.h @@ -50,6 +50,7 @@ inline const DeclaredOut* declared(unsigned long provider, int slot) {0x01acd177, 40, 1, 8, no_argument, no_argument, 0}, // find for device {0xcef4fac0, 3, 3, 0, 2, 4, 8}, // gamertag interface: buffer, &used {0x37e56907, 15, 0, 16, no_argument, no_argument, 0}, // connectivity hint: four words + {0x0dd112ac, 3, 1, 8, no_argument, no_argument, 0}, // XStoreCreateContext: &context }; for (const DeclaredOut& entry : table) if (entry.provider == provider && entry.slot == slot) return &entry; diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index a42909ac4..09c2ec9db 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -6,7 +6,8 @@ // so that the lookup of "QueryApiImpl" returns a wrapper. The wrapper hands out proxy objects whose // methods log their first calls ("x2w-runtime") and forward to the real object. // -// X2W_FAKE_USER=1 additionally answers the user API for one local user (see fake_user below). +// X2W_FAKE_USER=1 additionally answers the user API for one local user (see fake_user below) +// and, while the proxy is on, XStoreCreateContext for that user (see area_call). #include "startup_stubs/api_trace.h" #include "startup_stubs/local_log.h" #include "startup_stubs/save_blob_pack.h" @@ -48,6 +49,9 @@ QueryApi real_query; constexpr unsigned long user_provider_data1 = 0x01acd177; constexpr u64 local_user_handle = 0x58325755'00000001ull; // not a pointer the runtime knows constexpr u64 local_user_id = 0x0009000012345678ull; +// XStoreImpl. Method 3 is XStoreCreateContext; the handle below is the offline context it writes. +constexpr unsigned long store_provider_data1 = 0x0dd112ac; +constexpr u64 store_context_handle = 0x58325753'00000001ull; // not a pointer the runtime knows bool fake_user() noexcept { return x2w_local::env_on("X2W_FAKE_USER"); } int user_provider = -1, save_provider = -1; // The user provider also hands out a second interface (iid cef4fac0...) whose slot 3 is @@ -882,9 +886,56 @@ bool area_call(unsigned long provider, int slot, u64* args, u64* result) *result = 0; return true; } + if (provider == store_provider_data1 && slot == 3) { + // XStoreCreateContext(user, &context). Vtable slot 3 of XStoreImpl + // (0dd112ac-7c24-448c-b92b-3960fb5bd30c): QueryInterface, AddRef, Release, then this. + // The public GDK takes the console user and writes an XStoreContextHandle. The VIctory + // runtime notes (github.com/Marvisak/VIctory, facts only) answer it offline by writing one + // context and returning success; catalog, licence and purchase methods stay unanswered. + // Only the local user is answered. A buffer that cannot be written is E_INVALIDARG. + if (args[0] != local_user_handle) return false; + if (!out(args[1], 8)) { + *result = 0x80070057; + return true; + } + *reinterpret_cast(args[1]) = store_context_handle; + *result = 0; + return true; + } return false; } +// Source-built check (tests/startup_stub_consumer.cpp). Both switches are required, as they are +// for a title: the proxy is installed only for X2W_RUNTIME_PROXY, and this answer only for the +// fake user. Returns 0 when the local user receives the context and a mutated provider still +// fails with E_FAIL without writing. +int store_method3_check() +{ + if (!x2w_local::env_on("X2W_RUNTIME_PROXY") || !fake_user()) return 2; + if (provider_count >= max_providers) return 3; + const int index = provider_count++; + provider_ids[index] = {}; + provider_ids[index].Data1 = store_provider_data1; + Proxy proxy{nullptr, nullptr, index}; + + u64 context = 0; + const u64 answered = forward<3>(&proxy, local_user_handle, reinterpret_cast(&context), 0, 0, 0, 0, 0, 0, 0, 0, 0); + if (answered != 0 || context != store_context_handle) return 4; + + u64 untouched = 0x1111111111111111ull; + provider_ids[index].Data1 = store_provider_data1 ^ 1u; // not the store provider + const u64 refused = forward<3>(&proxy, local_user_handle, reinterpret_cast(&untouched), 0, 0, 0, 0, 0, 0, 0, 0, 0); + if (refused != 0x80004005 || untouched != 0x1111111111111111ull) return 5; + provider_ids[index].Data1 = store_provider_data1; + + const u64 missing = forward<3>(&proxy, local_user_handle, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + if (missing != 0x80070057) return 6; + + std::printf("store context %016llx\n", static_cast(context)); + std::printf("store refused %08llx\n", static_cast(refused & 0xffffffffu)); + return 0; +} + // Persistent local storage: the root of a drive (X2W_STORAGE_PATH, e.g. "S:\\", mapped by the run // script onto a folder outside the game) with the quota from the manifest (X2W_STORAGE_MB). struct StorageObject { void* const* vtable; }; @@ -949,6 +1000,8 @@ void* storage_object() } } // namespace +int x2w_store_method3_check() { return store_method3_check(); } + BOOL WINAPI DllMain(HINSTANCE, DWORD reason, void*) { if (reason == DLL_PROCESS_ATTACH && x2w_local::env_on("X2W_RUNTIME_PROXY")) { diff --git a/tests/startup_stub_check.py b/tests/startup_stub_check.py index 3fbdf5967..584386f70 100644 --- a/tests/startup_stub_check.py +++ b/tests/startup_stub_check.py @@ -106,6 +106,16 @@ if not ok: failures.append(f"dstorage page-array control: exit {run.returncode}, stdout {run.stdout.strip()!r}") +store_env = dict(env, X2W_RUNTIME_PROXY="1", X2W_FAKE_USER="1") +run = subprocess.run([consumer, "store"], capture_output=True, text=True, env=store_env, timeout=20) +traps_after = open(log, encoding="ascii").read().count("x2w-trap ") if os.path.exists(log) else 0 +ok = (run.returncode == 0 and "store context 5832575300000001" in run.stdout + and "store refused 80004005" in run.stdout and "x2w-trap" not in run.stderr + and traps_after == len(cases)) +print(f"store context: exit={run.returncode} {'ok' if ok else 'MISMATCH'}") +if not ok: + failures.append(f"store context: exit {run.returncode}, stdout {run.stdout.strip()!r}, stderr {run.stderr.strip()!r}") + if failures: print("FAIL") for f in failures: diff --git a/tests/startup_stub_consumer.cpp b/tests/startup_stub_consumer.cpp index 6e7579f52..874abb6e4 100644 --- a/tests/startup_stub_consumer.cpp +++ b/tests/startup_stub_consumer.cpp @@ -7,6 +7,7 @@ // physical -> XMemAllocatePhysicalPages/XMemFreePhysicalPages round trip (no trap expected) // dstorage -> DirectStorage multi-page RFC 1950 zlib request, BCPack decode and failure controls (Refs #1139, #1144) // dstorage-pages -> page-array entries replaced, or made unreadable, between EnqueueRequest and Submit +// store -> XStoreCreateContext for the local user, and the same call on a mutated provider (Refs #1147) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -31,6 +32,7 @@ extern "C" __declspec(dllimport) void* WINAPI XMemVirtualAlloc(void* address, SI ULONGLONG attributes, DWORD protection); extern "C" __declspec(dllimport) void* WINAPI XMemMapPhysicalPages(void* base, ULONG_PTR count, const ULONG_PTR* tokens); +int x2w_store_method3_check(); namespace { @@ -1630,5 +1632,6 @@ int main(int argc, char** argv) std::puts("dstorage ok"); return 0; } + if (!std::strcmp(which, "store")) return x2w_store_method3_check(); return 2; } From b6522d1935a9f73ff782e177ffb728b590084fe9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 15:52:20 +0300 Subject: [PATCH 130/775] startup: check the DirectStorage file read above 4 GiB src/startup_stubs/dstorage_file_read.h reads a DirectStorage file request into the staging buffer through an OVERLAPPED position split into low and high 32-bit halves. Its only direct check, startup_storage_file_range, uses a 5-byte file, and the stand-in tests that load XCRDAPI.dll (startup_stubs, startup_storage_directory_batch) read small synthetic files. Single-point mutants that zero the high half, shift it by 31 instead of 32, or take the file size from its low 32 bits left all three passing. startup_dstorage_file_read writes four 4-byte runs into a sparse temporary file of 4 GiB + 20 bytes: at 0x10, above 2 GiB, across 4 GiB and at the end of the file 4 GiB above the first run. It reads each back with hand-written expected bytes and checks that ranges one byte past EOF above 4 GiB are rejected without touching the staging buffer. Each of the three mutants above now fails it. The startup_dstorage_file_read_alias_control run expects the low run's bytes at the high offset and must fail. Both exit 77 where the temporary folder does not take sparse files, before anything is written. --- CMakeLists.txt | 9 ++ docs/startup-runtime.md | 3 + tests/startup_dstorage_file_read_check.cpp | 112 +++++++++++++++++++++ 3 files changed, 124 insertions(+) create mode 100644 tests/startup_dstorage_file_read_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7dc782fe7..6afa6f496 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -337,6 +337,15 @@ add_executable(startup_storage_file_range tests/startup_storage_file_range.cpp) target_compile_features(startup_storage_file_range PRIVATE cxx_std_17) target_include_directories(startup_storage_file_range PRIVATE src) add_test(NAME startup_storage_file_range COMMAND startup_storage_file_range) +# The same read at offsets that need the high half of the OVERLAPPED position, in a sparse +# 4 GiB + 20 byte temporary file (src/startup_stubs/dstorage_file_read.h). 77 without sparse files. +add_executable(startup_dstorage_file_read_check tests/startup_dstorage_file_read_check.cpp) +target_compile_features(startup_dstorage_file_read_check PRIVATE cxx_std_17) +target_include_directories(startup_dstorage_file_read_check PRIVATE src) +add_test(NAME startup_dstorage_file_read COMMAND startup_dstorage_file_read_check) +add_test(NAME startup_dstorage_file_read_alias_control COMMAND startup_dstorage_file_read_check --mutate alias) +set_tests_properties(startup_dstorage_file_read startup_dstorage_file_read_alias_control PROPERTIES SKIP_RETURN_CODE 77) +set_tests_properties(startup_dstorage_file_read_alias_control PROPERTIES WILL_FAIL TRUE) add_executable(startup_inflate_status tests/startup_inflate_status.cpp) target_compile_features(startup_inflate_status PRIVATE cxx_std_17) target_include_directories(startup_inflate_status PRIVATE src) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index b99199b5b..92403ee7a 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -402,6 +402,9 @@ These are measured on one executable; treat them as hypotheses for others. - **DirectStorage file ranges.** A nonempty file request checks its byte offset and length against the current file size before allocating the staging buffer. A range ending at EOF is valid. An overrun or short read fails the queue request and preserves the destination. + `ctest --preset dev --no-tests=error -R '^startup_dstorage_file_read' -V` reads + `src/startup_stubs/dstorage_file_read.h` at offsets above 2 GiB, across 4 GiB and at EOF above + 4 GiB in a sparse temporary file, and skips (77) where the temporary folder has no sparse files. The `startup_storage_directory_batch` fixture submits ten requests across two synthetic RDS5/ETPF files on one queue. In each file, moving the first absolute source offset by 896 KiB selects a different valid 28-byte zlib stream. Both return success and produce 4096 bytes. Comparing the diff --git a/tests/startup_dstorage_file_read_check.cpp b/tests/startup_dstorage_file_read_check.cpp new file mode 100644 index 000000000..4b9ec2c48 --- /dev/null +++ b/tests/startup_dstorage_file_read_check.cpp @@ -0,0 +1,112 @@ +// Checks src/startup_stubs/dstorage_file_read.h at file offsets that need the high 32 bits of the +// OVERLAPPED position. The file is a sparse temporary file of 4 GiB + 20 bytes, so only the four +// written runs take space on disk. Without sparse-file support the check exits 77 before it writes +// anything, since a plain file would be zero-filled up to 4 GiB. +// --mutate alias: expect the bytes of the run 4 GiB lower at the high offset (a negative control). +#include "startup_stubs/dstorage_file_read.h" + +#include + +#include +#include + +namespace { +using Bytes = std::vector; +int failures; + +// The four runs. The positions are written as literal OVERLAPPED halves, not from a 64-bit offset. +struct Run { DWORD low, high; unsigned char bytes[4]; }; +constexpr Run low_alias{0x00000010, 0, {0xA1, 0xA2, 0xA3, 0xA4}}; // 0x0'0000'0010 +constexpr Run above_2g{0x80000010, 0, {0xD1, 0xD2, 0xD3, 0xD4}}; // 0x0'8000'0010 +constexpr Run across_4g{0xFFFFFFFE, 0, {0xC1, 0xC2, 0xC3, 0xC4}}; // 0x0'FFFF'FFFE .. 0x1'0000'0001 +constexpr Run above_4g{0x00000010, 1, {0xB1, 0xB2, 0xB3, 0xB4}}; // 0x1'0000'0010, ends the file +constexpr std::uint64_t file_size = 0x100000014; + +bool write_run(HANDLE file, const Run& run) +{ + OVERLAPPED position{}; + position.Offset = run.low; + position.OffsetHigh = run.high; + DWORD written = 0; + return WriteFile(file, run.bytes, sizeof(run.bytes), &written, &position) && written == sizeof(run.bytes); +} + +void read(const char* name, HANDLE file, std::uint64_t offset, const unsigned char (&expected)[4]) +{ + Bytes staging; + if (!x2w_startup::read_storage_file(file, offset, 4, staging)) { + std::printf("FAIL %s: read at 0x%llx failed\n", name, static_cast(offset)); + ++failures; + } else if (staging != Bytes(expected, expected + 4)) { + std::printf("FAIL %s: read at 0x%llx gave %zu bytes %02x %02x %02x %02x, expected %02x %02x %02x %02x\n", + name, static_cast(offset), staging.size(), + staging.size() > 0 ? staging[0] : 0, staging.size() > 1 ? staging[1] : 0, + staging.size() > 2 ? staging[2] : 0, staging.size() > 3 ? staging[3] : 0, + expected[0], expected[1], expected[2], expected[3]); + ++failures; + } +} + +void rejected(const char* name, HANDLE file, std::uint64_t offset, DWORD count) +{ + Bytes staging{0x5A, 0x5B}; + const auto capacity = staging.capacity(); + if (x2w_startup::read_storage_file(file, offset, count, staging) || staging != Bytes{0x5A, 0x5B} || + staging.capacity() != capacity) { + std::printf("FAIL %s: offset 0x%llx count %lu returned success or changed staging\n", name, + static_cast(offset), count); + ++failures; + } +} +} // namespace + +int main(int argc, char** argv) +{ + const bool alias = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "alias") == 0; + if (argc > 1 && !alias) { + std::printf("usage: startup_dstorage_file_read_check [--mutate alias]\n"); + return 2; + } + + wchar_t directory[MAX_PATH]{}, path[MAX_PATH]{}; + if (!GetTempPathW(MAX_PATH, directory) || !GetTempFileNameW(directory, L"x2w", 0, path)) return 1; + HANDLE file = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + if (file == INVALID_HANDLE_VALUE) { DeleteFileW(path); return 1; } + DWORD returned = 0; + BY_HANDLE_FILE_INFORMATION info{}; + if (!DeviceIoControl(file, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &returned, nullptr) || + !GetFileInformationByHandle(file, &info) || !(info.dwFileAttributes & FILE_ATTRIBUTE_SPARSE_FILE)) { + std::printf("SKIP: the temporary folder does not take sparse files (error %lu)\n", GetLastError()); + CloseHandle(file); + return 77; + } + if (!write_run(file, low_alias) || !write_run(file, above_2g) || !write_run(file, across_4g) || + !write_run(file, above_4g)) { + std::printf("FAIL: could not write the sparse runs (error %lu)\n", GetLastError()); + CloseHandle(file); + return 1; + } + LARGE_INTEGER length{}; + if (!GetFileSizeEx(file, &length) || static_cast(length.QuadPart) != file_size) { + std::printf("FAIL: file size 0x%llx, expected 0x%llx\n", static_cast(length.QuadPart), + static_cast(file_size)); + CloseHandle(file); + return 1; + } + + read("low run", file, 0x10, low_alias.bytes); + read("run above 2 GiB", file, 0x80000010, above_2g.bytes); + read("run across 4 GiB", file, 0xFFFFFFFE, across_4g.bytes); + // The last four bytes of the file, at the offset 4 GiB above the low run. + read("run above 4 GiB, ending at EOF", file, 0x100000010, alias ? low_alias.bytes : above_4g.bytes); + + // The range check compares 64-bit values. + rejected("one byte past EOF above 4 GiB", file, 0x100000011, 4); + rejected("offset past EOF above 4 GiB", file, 0x100000015, 1); + + CloseHandle(file); + if (failures) return 1; + std::printf("dstorage file read: offsets above 2 and 4 GiB exact\n"); + return 0; +} From b61a2359b980ecdc816ad4848dee9c4fa9eadc14 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:55:46 +0100 Subject: [PATCH 131/775] startup_stubs: refuse zero-extent present surfaces --- docs/startup-runtime.md | 2 +- src/startup_stubs/present_view_format.h | 2 +- tests/startup_present_view_check.cpp | 10 +++++++++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 3178da59f..e736d7ce1 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -30,7 +30,7 @@ records. The control expects the first blend patch to win and must fail. ## Output window and fallback diagnostics The desktop swap chain has its own top-level window, class `X2WOutputWindow`. -The presenter only samples single-sample 2D surfaces without +The presenter only samples non-empty single-sample 2D surfaces without `D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE` and with a supported view format (`src/startup_stubs/present_view_format.h`), and marks itself failed if closing its command list fails. diff --git a/src/startup_stubs/present_view_format.h b/src/startup_stubs/present_view_format.h index fc96f33aa..7640c9638 100644 --- a/src/startup_stubs/present_view_format.h +++ b/src/startup_stubs/present_view_format.h @@ -45,7 +45,7 @@ inline DXGI_FORMAT present_view_format(DXGI_FORMAT format) inline bool present_surface_supported(const D3D12_RESOURCE_DESC& desc) { return desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && - desc.SampleDesc.Count == 1 && + desc.SampleDesc.Count == 1 && desc.Width != 0 && desc.Height != 0 && (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == 0 && present_view_format(desc.Format) != DXGI_FORMAT_UNKNOWN; } diff --git a/tests/startup_present_view_check.cpp b/tests/startup_present_view_check.cpp index 8c3c474fc..05e16a010 100644 --- a/tests/startup_present_view_check.cpp +++ b/tests/startup_present_view_check.cpp @@ -101,6 +101,14 @@ void surface_support() zero_samples.SampleDesc.Count = 0; expect_supported("samples0 refused", zero_samples, false); + D3D12_RESOURCE_DESC zero_width = tex2d; + zero_width.Width = 0; + expect_supported("width0 refused", zero_width, false); + + D3D12_RESOURCE_DESC zero_height = tex2d; + zero_height.Height = 0; + expect_supported("height0 refused", zero_height, false); + D3D12_RESOURCE_DESC unknown_fmt = tex2d; unknown_fmt.Format = DXGI_FORMAT_UNKNOWN; expect_supported("unknown fmt refused", unknown_fmt, false); @@ -327,7 +335,7 @@ int main(int argc, char** argv) std::printf("startup_present_view: %d FAILED\n", failures); return 1; } - std::printf("startup_present_view: PASS (4 mapped, 6 typed, 18 refused, 2 invalid, 11 surface checks)\n"); + std::printf("startup_present_view: PASS (4 mapped, 6 typed, 18 refused, 2 invalid, 13 surface checks)\n"); return 0; } try { From 7ba209aab55de98c07c2afe257ba353d3bd885f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 15:56:15 +0300 Subject: [PATCH 132/775] startup: check the null binding cause labels src/startup_stubs/null_binding_cause.h classifies each null binding of a translated draw. The device counts it at the index given by the cause's enum value and prints slots 0 to 4 of the x2w-render totals line under the fixed labels entry, buffer, token, wrapper and dimension. The only test of the header, startup_null_views_, counts causes by enum name, so it cannot see which slot a cause lands in. Single-point mutants that swap two enumerators or two entries of null_cause_names passed startup_null_views_warp, and a mutant that sets none to 0 failed it only through an out-of-bounds write. startup_null_cause_labels includes the header without a device. For one binding per cause, built the way the texture and buffer bindings build their facts, it checks the slot and the header's name for it. It then counts a frame in which each cause occurs a different power of two times and compares the totals text, formatted as the device does and again from null_cause_names, with a hand-written line. The buffer-token control expects those two slots swapped and must fail. --- CMakeLists.txt | 8 ++ docs/startup-runtime.md | 5 +- tests/startup_null_cause_labels_check.cpp | 150 ++++++++++++++++++++++ 3 files changed, 162 insertions(+), 1 deletion(-) create mode 100644 tests/startup_null_cause_labels_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7dc782fe7..1312968df 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -310,6 +310,14 @@ foreach(adapter IN ITEMS hardware warp) add_test(NAME startup_null_views_${adapter} COMMAND startup_null_views_check ${adapter}) endforeach() set_tests_properties(startup_null_views_hardware PROPERTIES SKIP_RETURN_CODE 77) +# The slot and label of the x2w-render totals line each null-binding cause is counted under +# (src/startup_stubs/null_binding_cause.h). The mutated run is the negative control. +add_executable(startup_null_cause_labels_check tests/startup_null_cause_labels_check.cpp) +target_include_directories(startup_null_cause_labels_check PRIVATE src) +target_compile_features(startup_null_cause_labels_check PRIVATE cxx_std_17) +add_test(NAME startup_null_cause_labels COMMAND startup_null_cause_labels_check) +add_test(NAME startup_null_cause_labels_buffer_token_control COMMAND startup_null_cause_labels_check --mutate buffer-token) +set_tests_properties(startup_null_cause_labels_buffer_token_control PROPERTIES WILL_FAIL TRUE) # The opt-in API trace reads only declared outputs; this checks the decision about what it observed # (argument index 0, two outputs, exact and short buffers, same value, partial comparison). add_executable(api_trace_check tests/api_trace_check.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index b99199b5b..b8200fce5 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -130,7 +130,10 @@ the five parts add up to N: The classification lives in `src/startup_stubs/null_binding_cause.h`. The source-built `startup_null_views_check` fixture checks every cause, that the parts sum to the total, and that valid bindings add nothing. It does not draw, so the counters in the totals line itself are checked -by reading a render log. +by reading a render log. The device prints the counts by cause value, so +`ctest --preset dev --no-tests=error -R "^startup_null_cause_labels(_buffer_token_control)?$" -V` +checks without a device that each cause lands in the slot printed under its label, and that the +header's names follow the same order. The control swaps the buffer and token slots and must fail. ## What is measured diff --git a/tests/startup_null_cause_labels_check.cpp b/tests/startup_null_cause_labels_check.cpp new file mode 100644 index 000000000..0d3811db4 --- /dev/null +++ b/tests/startup_null_cause_labels_check.cpp @@ -0,0 +1,150 @@ +// Checks src/startup_stubs/null_binding_cause.h without a device: the slot of the x2w-render totals +// line each cause is counted in, and the label printed for that slot. The device indexes its counts +// by the cause's value and prints slots 0 to 4 as entry, buffer, token, wrapper and dimension. +#include "startup_stubs/null_binding_cause.h" + +#include +#include + +namespace { +using x2w_local::BindingFacts; +int failures, cases; + +const char* const labels[] = {"entry", "buffer", "token", "wrapper", "dimension"}; + +// Facts as the texture binding builds them: from a table, with a readable entry carrying a known +// view token for a resource wrapper of the shader's dimension. +BindingFacts texture() +{ + BindingFacts f; + f.texture = f.from_table = f.entry_readable = f.token_magic = f.token_known = f.resource_wrapper = true; + return f; +} + +// Facts as the buffer binding builds them for a table entry the title wrote itself (no view token). +BindingFacts table_buffer(bool bound) +{ + BindingFacts f; + f.from_table = f.entry_readable = true; + f.bound = bound; + return f; +} + +int slot_of(const BindingFacts& f) +{ + return static_cast(x2w_local::classify_null_binding(f)); +} + +void counted(const char* name, const BindingFacts& f, int slot) +{ + ++cases; + const int got = slot_of(f); + if (got != slot) { + std::printf("FAIL %s: slot %d, expected %d (%s)\n", name, got, slot, labels[slot]); + ++failures; + } else if (std::strcmp(x2w_local::null_cause_names[got], labels[slot]) != 0) { + std::printf("FAIL %s: slot %d named \"%s\", expected \"%s\"\n", name, got, x2w_local::null_cause_names[got], + labels[slot]); + ++failures; + } +} + +void same_text(const char* name, const char* got, const char* expected) +{ + ++cases; + if (std::strcmp(got, expected) != 0) { + std::printf("FAIL %s:\n got %s\n expected %s\n", name, got, expected); + ++failures; + } +} +} // namespace + +int main(int argc, char** argv) +{ + // --mutate buffer-token: the expectations of a totals line that prints the unknown-token count + // under "buffer" and the buffer count under "token" (a negative control: the check must fail). + const bool swapped = argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "buffer-token") == 0; + if (argc > 1 && !swapped) { + std::printf("unknown mutation\n"); + return 2; + } + const int entry = 0, buffer = swapped ? 2 : 1, token = swapped ? 1 : 2, wrapper = 3, dimension = 4; + + if (x2w_local::null_cause_count != 5) { + std::printf("FAIL: %d causes, expected 5\n", x2w_local::null_cause_count); + return 1; + } + for (int i = 0; i < 5; ++i) { + ++cases; + if (std::strcmp(x2w_local::null_cause_names[i], labels[i]) != 0) { + std::printf("FAIL: slot %d named \"%s\", expected \"%s\"\n", i, x2w_local::null_cause_names[i], labels[i]); + ++failures; + } + } + + // One binding per cause, each counted in its own slot. + BindingFacts f = texture(); + f.entry_readable = f.token_magic = f.token_known = f.resource_wrapper = false; // an unreadable entry reads as zeros + counted("texture with an unreadable table entry", f, entry); + counted("table buffer without a readable range", table_buffer(false), buffer); + f = BindingFacts{}; + counted("vertex buffer without a readable range", f, buffer); + f = texture(); + f.token_known = f.resource_wrapper = false; + counted("texture whose view id the wrapper never issued", f, token); + f = table_buffer(false); + f.token_magic = true; + counted("table buffer whose view id the wrapper never issued", f, token); + f = texture(); + f.resource_wrapper = false; + counted("texture view without a resource wrapper", f, wrapper); + f = texture(); + f.dimension_matches = false; + counted("texture view of another dimension", f, dimension); + + // A frame of bindings in which each cause occurs a different power of two times, so a count + // printed under another label changes the line. Valid bindings add nothing. + struct Binding { + BindingFacts facts; + int times; + }; + BindingFacts unreadable = texture(), unknown = texture(), no_wrapper = texture(), mismatch = texture(); + unreadable.entry_readable = unreadable.token_magic = unreadable.token_known = unreadable.resource_wrapper = false; + unknown.token_known = unknown.resource_wrapper = false; + no_wrapper.resource_wrapper = false; + mismatch.dimension_matches = false; + const Binding frame[] = { + {texture(), 3}, {table_buffer(true), 2}, {unreadable, 1}, {table_buffer(false), 2}, + {unknown, 4}, {no_wrapper, 8}, {mismatch, 16}, + }; + long total = 0, by_slot[5] = {}; + for (const Binding& b : frame) { + const int slot = slot_of(b.facts); + if (slot == static_cast(x2w_local::NullCause::none)) continue; + if (slot < 0 || slot >= 5) { + std::printf("FAIL: a null binding in slot %d, outside the five printed\n", slot); + return 1; + } + total += b.times; + by_slot[slot] += b.times; + } + // The device's format string, with the slots in the order it passes them. + char line[160]; + std::snprintf(line, sizeof(line), "null bindings %ld (entry %ld, buffer %ld, token %ld, wrapper %ld, dimension %ld)", + total, by_slot[0], by_slot[1], by_slot[2], by_slot[3], by_slot[4]); + const char* const expected = swapped ? "null bindings 31 (entry 1, buffer 4, token 2, wrapper 8, dimension 16)" + : "null bindings 31 (entry 1, buffer 2, token 4, wrapper 8, dimension 16)"; + same_text("totals line", line, expected); + // The same counts labelled from the header's names. + const char* const* n = x2w_local::null_cause_names; + std::snprintf(line, sizeof(line), "null bindings %ld (%s %ld, %s %ld, %s %ld, %s %ld, %s %ld)", total, n[0], by_slot[0], + n[1], by_slot[1], n[2], by_slot[2], n[3], by_slot[3], n[4], by_slot[4]); + same_text("totals line from the header's names", line, expected); + + if (failures) { + std::printf("startup_null_cause_labels: %d of %d FAILED\n", failures, cases); + return 1; + } + std::printf("startup_null_cause_labels: PASS (%d cases)\n", cases); + return 0; +} From 271af14ea284095efb2570520da9ac2b27d4bac7 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:57:01 +0800 Subject: [PATCH 133/775] docs: record the array-atomics probe on Intel Arc Xe2 gpu_alias_lookup_writes_hardware fails on the Arc 140T at 06e2ff78 with the four buffers reading 256, 192, 128 and 64 against 64 expected. That is the same per-buffer pattern already recorded for an Intel UHD Graphics 770, so the split follows the Intel driver rather than one integrated adapter. The rest of the fixture matches on this adapter: the add and sub words keep their expected values and the 2,331-record title-address run checks 147,456 words with zero mismatches. Docs only. --- docs/experiments.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/experiments.md b/docs/experiments.md index 691357d94..394898ec7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6328,6 +6328,7 @@ Measured at commit `55cea41` on Windows 11 build 26300, with the debug layer una - At commit `185b9d6c` on Windows 11 build 26200 with the debug layer enabled, an RDNA 3 adapter reproduces the same probe failure: an AMD Radeon RX 7900 XTX (device `744c`, driver 32.0.32029.2010) reads 256 in each of the four buffers, with the title-address fixture recording zero mismatches across all 1,047 records and 147,454 checked words and zero D3D12 debug errors or warnings ([report](https://github.com/R0Y00/Xbox2Windows/issues/369)). - At commit `06e2ff78` on Windows 11 build 26300.9974 with the debug layer enabled, an Intel Arc 140T (device `7d51`, driver 32.0.101.8132) passed `gpu_alias_window_hardware`: two pages at offset `0x11234` over `0x1e000` bytes, relative identity and roundtrip both confirmed, the negative readback unchanged and zero mismatches, with zero D3D12 debug errors or warnings. - Signed zeros in `gpu_alias_lookup_writes`. Float min and max replace only on a strict `<` or `>`, so `-0.0` and `+0.0` tie and the stored word is kept. The fixture expects this, not IEEE `minNum`/`maxNum`, and compares raw bits. Four words get one record each: min and max, each from `+0` with a `-0` candidate and from `-0` with a `+0` candidate. All four must keep their starting bits. Four more words start at a signed zero and have 256 contenders each. Every third contender alternates `-0` and `+0`, and the rest are strictly negative or strictly positive inputs. On two of these words a strictly smaller (min) or larger (max) input must win. On the other two every contender ties or loses, so the starting zero must survive. A zero that could win is never contended by the opposite zero, so every expected word is deterministic. A ninth max word has only negative contenders and is seeded at negative infinity, because under a strict `>` no negative input can replace a zero. The highest negative must win. On Windows 11 build 26300 with the debug layer enabled, WARP 10.0.26100.10068 and an NVIDIA GeForce RTX 3060 (driver 32.0.16.1742) passed in the `dev` and `release` presets: 2,331 records and 0 mismatches. An Intel UHD Graphics 770 (driver 32.0.101.7092) matched all 2,331 records and all nine signed-zero words too, but failed as before on the array-atomics probe (`256,192,128,64`, [#369](https://github.com/R0Y00/Xbox2Windows/issues/369)). Replacing on equality (`<=`/`>=`) gave 5 mismatches on both adapters, all on signed-zero words. A compare-exchange loop without retry still passed on WARP. On the RTX 3060 it failed in 3 of 3 runs with 5 mismatches: the original min and max words and the three contended words a strict input must win. +- At commit `06e2ff78` on Windows 11 build 26300.9974 with the debug layer enabled, an Intel Arc 140T (device `7d51`, driver 32.0.101.8132) reproduces the Intel per-buffer pattern recorded below for the UHD Graphics 770: the four buffers read 256, 192, 128 and 64 against 64 expected, so the over-count differs per buffer instead of repeating one value. The rest of the fixture matches: the add and sub words keep their expected values, and the 2,331-record title-address run checks 147,456 words with zero mismatches. - The [RX 6500 report](https://github.com/R0Y00/Xbox2Windows/pull/793) used commit `a4ade3032fec08767ed411cc83834a3543c626f2`, driver 32.0.21045.29003, From 8a03ab307bdb2e0cb8b3e0c44ceb57c76b7af889 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 15:57:15 +0300 Subject: [PATCH 134/775] tests: remove the startup_stubs trap-log folder on exit startup_stub_check.py created its trap log in tempfile.mkdtemp() and never removed the folder, so every startup_stubs run left an x2w_trap_* folder with a trap.log of about 17 KB in %TEMP%. Register shutil.rmtree for that folder with atexit, which also runs when the check fails through sys.exit(1). --- tests/startup_stub_check.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/startup_stub_check.py b/tests/startup_stub_check.py index 3fbdf5967..2ac3a7e26 100644 --- a/tests/startup_stub_check.py +++ b/tests/startup_stub_check.py @@ -8,10 +8,12 @@ 3. Controls: the 'none' scenario exits 0 and writes no trap line; the physical-page round trip in xmem.dll still works next to the traps. """ +import atexit import ctypes import ctypes.wintypes as wt import os import re +import shutil import subprocess import sys import tempfile @@ -61,7 +63,10 @@ env = dict(os.environ) env["PATH"] = os.pathsep.join(sorted({os.path.dirname(os.path.abspath(p)) for p in dlls})) + os.pathsep + env["PATH"] -log = os.path.join(tempfile.mkdtemp(prefix="x2w_trap_"), "trap.log") +# The trap log lives in a fresh folder that is removed when the check exits, pass or fail. +log_dir = tempfile.mkdtemp(prefix="x2w_trap_") +atexit.register(shutil.rmtree, log_dir, ignore_errors=True) +log = os.path.join(log_dir, "trap.log") env["X2W_TRAP_LOG"] = log cases = [ From c0ade401ead7c5793e5b673351ba71d686366ed7 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 20:58:35 +0800 Subject: [PATCH 135/775] Mock the non-Windows commit-budget test path --- tests/host_commit_check.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/host_commit_check.py b/tests/host_commit_check.py index 82be919a1..36d93a428 100644 --- a/tests/host_commit_check.py +++ b/tests/host_commit_check.py @@ -77,7 +77,8 @@ def test_native_windows_budget_has_valid_counts(self): self.assertTrue(require_commit_budget(0, budget)["meets_minimum"]) def test_winapi_failure_and_unsupported_host(self): - with self.assertRaisesRegex(OSError, "Windows host"): + with patch("host_commit.sys.platform", "linux"), \ + self.assertRaisesRegex(OSError, "Windows host"): read_host_commit() native = NativeGetPerformance(success=False) with patch("host_commit.sys.platform", "win32"), \ From 4da7bd7f93d747a38954b374ea40400ad254aec1 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:54:23 +0100 Subject: [PATCH 136/775] fix: guard slice footprint byte spans and uploads against invalid indices AI-assisted; commands listed were executed locally. --- src/startup_stubs/slice_footprints.h | 13 ++- tests/startup_plane_refresh.cpp | 162 +++++++++++++++++++++++++++ 2 files changed, 174 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/slice_footprints.h b/src/startup_stubs/slice_footprints.h index c6f453874..c1ea77ffe 100644 --- a/src/startup_stubs/slice_footprints.h +++ b/src/startup_stubs/slice_footprints.h @@ -38,14 +38,25 @@ struct SliceFootprints { device->GetCopyableFootprints(&desc, 0, count, 0, placed, rows, row_bytes, &size); } + // Bytes from the start of subresource i to the end of its last row; 0 when there is nothing to + // span: an index past the arrays, or a plan whose entry was never filled (no device, unsupported + // format) and so has no rows or depth. Callers treat 0 as an empty copy. UINT64 bytes(UINT i) const { - return UINT64{placed[i].Footprint.RowPitch} * (UINT64{placed[i].Footprint.Depth} * rows[i] - 1) + row_bytes[i]; + if (i >= max_mips * 2) return 0; + const UINT64 depth = placed[i].Footprint.Depth, row_count = rows[i]; + if (!depth || !row_count) return 0; + return UINT64{placed[i].Footprint.RowPitch} * (depth * row_count - 1) + row_bytes[i]; } void upload(ID3D12GraphicsCommandList* list, ID3D12Resource* texture, ID3D12Resource* upload_buffer, UINT mips, UINT slices, UINT slice, UINT i, UINT64 offset) const { + // Nothing is copied for a missing object, a plan without footprints, or an index outside the plan, + // the mip count or the slice count. mips <= max_mips also keeps the subresource index within 32 bits. + if (!list || !texture || !upload_buffer || !mips || mips > max_mips || !slices || slice >= slices || + i >= count || size == UINT64_MAX) + return; D3D12_TEXTURE_COPY_LOCATION from{upload_buffer, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; from.PlacedFootprint = {offset, placed[i].Footprint}; D3D12_TEXTURE_COPY_LOCATION to{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; diff --git a/tests/startup_plane_refresh.cpp b/tests/startup_plane_refresh.cpp index 8ddac2638..d6057351b 100644 --- a/tests/startup_plane_refresh.cpp +++ b/tests/startup_plane_refresh.cpp @@ -3,6 +3,10 @@ #include "startup_stubs/slice_footprints.h" #include +#include +#include +#include +#include namespace { constexpr UINT width = 17, height = 3; @@ -72,11 +76,169 @@ void run(ID3D12Device* device, bool stale) !x2w_startup::recheck_cpu_texture(other, plan.size, 15)) throw std::runtime_error("Unexpected CPU texture refresh interval"); } + +// A stand-in command list: a COM object starts with a pointer to its method table, and slot 16 is +// CopyTextureRegion in the declaration order of ID3D12GraphicsCommandListVtbl in d3d12.h. Every other +// slot ends the run, so a call to another method fails. +constexpr std::size_t list_slots = 64, copy_slot = 16; + +template +void unexpected_slot() +{ + std::printf("FAIL unexpected call to command list slot %zu\n", N); + std::fflush(stdout); + std::_Exit(1); +} + +template +std::array trap_table(std::index_sequence) +{ + return {reinterpret_cast(&unexpected_slot)...}; +} + +struct CopyCall { + int calls; + UINT subresource; + UINT64 offset; + ID3D12Resource *destination, *source; +}; +CopyCall last_copy; + +void STDMETHODCALLTYPE fake_copy(ID3D12GraphicsCommandList*, const D3D12_TEXTURE_COPY_LOCATION* to, UINT, UINT, UINT, + const D3D12_TEXTURE_COPY_LOCATION* from, const D3D12_BOX*) +{ + last_copy = {last_copy.calls + 1, to->SubresourceIndex, from->PlacedFootprint.Offset, to->pResource, from->pResource}; +} + +struct FakeList { + const void* const* table; +}; + +int guard_failures; + +void guard_expect(bool ok, const char* name) +{ + if (ok) return; + std::printf("FAIL %s\n", name); + ++guard_failures; +} + +D3D12_RESOURCE_DESC image(DXGI_FORMAT format, UINT64 width, UINT height) +{ + return {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; +} + +// What D3D12CalcSubresource defines: mip + array slice * mips + plane * mips * array size. +UINT calc_subresource(UINT mip, UINT slice, UINT plane, UINT mips, UINT slices) +{ + return mip + slice * mips + plane * mips * slices; +} + +// SliceFootprints::bytes() and upload() need no GPU: a plan built without a device is filled by hand. +// Invalid requests must give 0 bytes and no copy instead of reading past the arrays, wrapping around +// 2^64 or dividing by zero. +void check_footprint_guards() +{ + using x2w_startup::SliceFootprints; + SliceFootprints plane(nullptr, image(DXGI_FORMAT_R8_UNORM, 17, 3), 1); + plane.placed[0].Footprint = {DXGI_FORMAT_R8_UNORM, 17, 3, 1, 256}; + plane.rows[0] = 3; + plane.row_bytes[0] = 17; + guard_expect(plane.bytes(0) == 256 * 2 + 17, "bytes: one plane ends after the last row, not the last pitch"); + guard_expect(plane.bytes(1) == 0, "bytes: index past count but in the arrays, never filled"); + guard_expect(plane.bytes(SliceFootprints::max_mips * 2) == 0, "bytes: index just past the arrays"); + guard_expect(plane.bytes(1000) == 0 && plane.bytes(UINT_MAX) == 0, "bytes: far index"); + guard_expect(plane.size == UINT64_MAX, "plan without a device has no size"); + + SliceFootprints yuv(nullptr, image(DXGI_FORMAT_NV12, 8, 4), 1); + yuv.placed[0].Footprint = {DXGI_FORMAT_R8_UNORM, 8, 4, 1, 256}; + yuv.rows[0] = 4; + yuv.row_bytes[0] = 8; + yuv.placed[1].Footprint = {DXGI_FORMAT_R8G8_UNORM, 4, 2, 1, 256}; + yuv.rows[1] = 2; + yuv.row_bytes[1] = 8; + guard_expect(yuv.bytes(0) == 256 * 3 + 8 && yuv.bytes(1) == 256 + 8, "bytes: NV12 luma then chroma"); + guard_expect(yuv.bytes(2) == 0, "bytes: NV12 index past both planes"); + + SliceFootprints odd(nullptr, image(DXGI_FORMAT_R8_UNORM, 1, 1), 1); + odd.placed[0].Footprint = {DXGI_FORMAT_R8_UNORM, 1, 0, 1, 256}; + odd.row_bytes[0] = 17; + guard_expect(odd.bytes(0) == 0, "bytes: no rows"); + odd.rows[0] = 3; + odd.placed[0].Footprint.Depth = 0; + guard_expect(odd.bytes(0) == 0, "bytes: no depth"); + odd.placed[0].Footprint.Depth = 1; + odd.placed[0].Footprint.RowPitch = 0; + guard_expect(odd.bytes(0) == 17, "bytes: zero pitch spans one row"); + odd.placed[0].Footprint.RowPitch = 256; + odd.placed[0].Footprint.Depth = 4; + guard_expect(odd.bytes(0) == 256 * 11 + 17, "bytes: depth slices of rows"); + const SliceFootprints unset(nullptr, image(DXGI_FORMAT_R8_UNORM, 1, 1), 1); + guard_expect(unset.bytes(0) == 0, "bytes: nothing filled in"); + + auto table = trap_table(std::make_index_sequence{}); + table[copy_slot] = reinterpret_cast(&fake_copy); + FakeList list_object{table.data()}; + auto* list = reinterpret_cast(&list_object); + auto* texture = reinterpret_cast(std::uintptr_t{0x10}); + auto* buffer = reinterpret_cast(std::uintptr_t{0x20}); + + // Valid requests: NV12 planes, then the second slice of a three-mip array and its last mip. + yuv.size = 0x1000; + for (UINT i = 0; i < 2; ++i) { + last_copy = {}; + yuv.upload(list, texture, buffer, 1, 1, 0, i, 0x300 + i); + guard_expect(last_copy.calls == 1 && last_copy.subresource == calc_subresource(0, 0, i, 1, 1) && + last_copy.offset == 0x300 + i && last_copy.destination == texture && last_copy.source == buffer, + "upload: NV12 plane copies into its own subresource"); + } + SliceFootprints chain(nullptr, image(DXGI_FORMAT_R8_UNORM, 4, 4), 3); + chain.size = 0x1000; + last_copy = {}; + chain.upload(list, texture, buffer, 3, 2, 1, 2, 0x40); + guard_expect(last_copy.calls == 1 && last_copy.subresource == calc_subresource(2, 1, 0, 3, 2) && last_copy.offset == 0x40, + "upload: slice 1 mip 2 of a three-mip, two-slice texture"); + + // Refused requests copy nothing, and do not reach the list. + struct Refused { + const char* name; + ID3D12GraphicsCommandList* list; + ID3D12Resource *texture, *buffer; + UINT mips, slices, slice, i; + }; + const Refused refused[] = { + {"no list", nullptr, texture, buffer, 3, 2, 1, 2}, + {"no texture", list, nullptr, buffer, 3, 2, 1, 2}, + {"no upload buffer", list, texture, nullptr, 3, 2, 1, 2}, + {"zero mips", list, texture, buffer, 0, 2, 1, 2}, + {"16 mips", list, texture, buffer, 16, 2, 1, 2}, + {"zero slices", list, texture, buffer, 3, 0, 0, 2}, + {"slice past the slices", list, texture, buffer, 3, 2, 2, 2}, + {"subresource past the plan", list, texture, buffer, 3, 2, 1, 3}, + {"subresource far past the plan", list, texture, buffer, 3, 2, 1, UINT_MAX}, + }; + for (const auto& item : refused) { + last_copy = {}; + chain.upload(item.list, item.texture, item.buffer, item.mips, item.slices, item.slice, item.i, 0x40); + char name[64]; + std::snprintf(name, sizeof(name), "upload: %s copies nothing", item.name); + guard_expect(last_copy.calls == 0, name); + } + const SliceFootprints without_footprints(nullptr, image(DXGI_FORMAT_R8_UNORM, 4, 4), 3); + last_copy = {}; + without_footprints.upload(list, texture, buffer, 3, 2, 1, 2, 0x40); + guard_expect(last_copy.calls == 0, "upload: a plan without footprints copies nothing"); + + if (guard_failures) throw std::runtime_error("Slice footprint guards failed"); + std::printf("slice footprint guards: PASS\n"); +} } // namespace int main() { try { + check_footprint_guards(); auto device = shim_create_device(); Microsoft::WRL::ComPtr factory; Microsoft::WRL::ComPtr adapter; From 53bbb4426ca3b8c27aaff8c4973c7803e4f83ae1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 15:59:10 +0300 Subject: [PATCH 137/775] runtime: check the per-adapter GPU usage total in either order xmem_gpu_usage::total() combines the per-LUID readings behind the XMemGetWorkingSetStatistics value at +8. Its documented rules do not depend on adapter order, but xmem_shim_working_set_aggregation tested the unknown-identity and partial-overlap rules only with the identified or larger adapter first, and tested the overflow guard only past the limit. Three single-point mutants left the aggregation, working_set and working_set_warp tests passing: same_devices() checking one direction only, unknown_active assigned instead of or-ed, and the overflow guard comparing with >= so a sum of exactly UINT64_MAX is declined. Add the two order-swapped cases (an unidentified active adapter before an identified active one, and a key subset before its superset), which must give no total, and a sum of exactly UINT64_MAX, which must be published. Each of the three mutants now fails the test. Ten further mutants (including dropping the enumeration_complete check, ignoring queried, counting aliases twice, a dropped guard, exact key comparison, max instead of sum, ignoring partial overlap, reading one segment group and an unknown node count read as zero) were already caught. --- docs/experiments.md | 2 +- tests/xmem_shim_check.cpp | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index bbff1e8dc..c10b1557b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5701,7 +5701,7 @@ A local scan of the inspected package's 16 DLLs together with this `xmem.dll` (` | `xmem_shim_query` | Graphics memory from `XMemAlloc` passes both BVH predicates and keeps the sentinel after `+0x30`, through the pseudo-handle and a real handle. After `XMemFree` the address reads as `MEM_FREE` with a clear tail. Heap memory fails the tail check, and an address outside user space returns `FALSE` without touching the buffer. | | `xmem_shim_working_set` | Selector `0x20000001` returns `TRUE` and writes only the qword at `+8` of a 128-byte buffer. Selector `0x20000002` returns `FALSE` with `ERROR_NOT_SUPPORTED` and leaves the buffer untouched; a null output returns `ERROR_INVALID_PARAMETER`. | | `xmem_shim_transfer_memory` | Verifies that `XMemTransferMemory` returns `FALSE` with `ERROR_NOT_SUPPORTED` under caller sequences (including partition 1 and 2 MiB / 16 MiB counts), leaving existing heap/graphics allocations, physical page grants, query registration, tools memory status and working-set statistics untouched. | -| `xmem_shim_working_set_aggregation` | Synthetic readings for the aggregation rules. Regression reference: the laptop readings above give no total when the two LUIDs have no identity, and a 64 MiB difference when both carry the same key. Also covered: Basic Render Driver aliases count once, distinct adapters of the same model with equal readings are summed, a genuine zero is published, and an all-failed, partly failed or incomplete enumeration, disagreeing aliases, an active adapter of unknown identity next to another active adapter, partly overlapping linked adapters and an overflowing sum give no total. Keys that differ only in case count once, must agree, and still give no total when they partly overlap. Malformed key query output (nothing written, an empty key, a length past the buffer, no terminator, an embedded terminator) gives no key. Per-node readings: usage only on node 1 of a linked pair is counted, and an unknown node count, a segment query that fails after a successful one (on the same node or a later node) and an overflow between segments or nodes give no total. | +| `xmem_shim_working_set_aggregation` | Synthetic readings for the aggregation rules. Regression reference: the laptop readings above give no total when the two LUIDs have no identity, and a 64 MiB difference when both carry the same key. Also covered: Basic Render Driver aliases count once, distinct adapters of the same model with equal readings are summed, a genuine zero is published, and an all-failed, partly failed or incomplete enumeration, disagreeing aliases, an active adapter of unknown identity next to another active adapter, partly overlapping linked adapters and an overflowing sum give no total. The unknown-identity and partial-overlap cases also run with the adapters swapped, and a sum of exactly `UINT64_MAX` is published. Run them with `ctest --preset dev --no-tests=error -R '^xmem_shim_working_set_aggregation$' -V`. Keys that differ only in case count once, must agree, and still give no total when they partly overlap. Malformed key query output (nothing written, an empty key, a length past the buffer, no terminator, an embedded terminator) gives no key. Per-node readings: usage only on node 1 of a linked pair is counted, and an unknown node count, a segment query that fails after a successful one (on the same node or a later node) and an overflow between segments or nodes give no total. | | `xmem_shim_working_set_warp`, `xmem_shim_working_set_hardware` | As the callers do, reads `+8` (zero on failure) before and after creating and releasing 64 MiB DEFAULT, UPLOAD and READBACK heaps and a 32 MiB committed buffer on a new device. Each creation must add at least the allocation size (`GetResourceAllocationInfo` for the buffer) and at most 4 MiB more, and each release must remove as much. Negative control: with the former `ERROR_NOT_SUPPORTED` stub every difference is 0 and both cases fail. Prints each DXGI adapter with its LUID, node count and PnP keys. The hardware case measures the first D3D12 adapter in high-performance order, or the first whose description contains `XBOX2WINDOWS_ADAPTER` (ignoring case; no match fails), and prints it. Skips (77) without the adapter or a D3D12 device. | ### Default allocation pair under the Windows loader and pe_map diff --git a/tests/xmem_shim_check.cpp b/tests/xmem_shim_check.cpp index dbb79b9ac..98b701d0d 100644 --- a/tests/xmem_shim_check.cpp +++ b/tests/xmem_shim_check.cpp @@ -457,7 +457,13 @@ bool aggregation_checks() {"alias_disagrees", {domain(64 * mib, {basic}), domain(32 * mib, {basic})}, true, std::nullopt}, {"unidentified_with_active", {domain(64 * mib, {gpu_a}), domain(64 * mib)}, true, std::nullopt}, {"linked_partial_overlap", {domain(64 * mib, {gpu_a, gpu_b}), domain(64 * mib, {gpu_a})}, true, std::nullopt}, + // The rules do not depend on adapter order: the two cases above with the adapters swapped. + {"unidentified_first", {domain(64 * mib), domain(64 * mib, {gpu_a})}, true, std::nullopt}, + {"linked_partial_overlap_second", {domain(64 * mib, {gpu_a}), domain(64 * mib, {gpu_a, gpu_b})}, true, + std::nullopt}, {"overflow", {domain(UINT64_MAX, {gpu_a}), domain(1, {gpu_b})}, true, std::nullopt}, + // A sum of exactly UINT64_MAX fits, so it is published. + {"sum_fits_exactly", {domain(UINT64_MAX - 1, {gpu_a}), domain(1, {gpu_b})}, true, UINT64_MAX}, // Registry keys match ignoring case, so a case variant of a key is the same device. {"mixed_case_alias", {domain(64 * mib, {gpu_a}), domain(64 * mib, {gpu_a_lower})}, true, 64 * mib}, {"mixed_case_alias_disagrees", {domain(64 * mib, {gpu_a}), domain(32 * mib, {gpu_a_lower})}, true, From d03a76c47fcc1369ddfb0c07ffad13ff3fb43463 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:59:16 +0800 Subject: [PATCH 138/775] docs: complete the DXR command group for Intel Xe2 The command in the independent BVH section runs dxr_pipeline, dxr_query and bvh_differential, but the Arc paragraph added in 1433 covered only the differential case. Add the five-ray result at 06e2ff78: both DXR checks return the same five outcomes (rays 0 and 3 hit instances 7 and 11 at distance 1, the other three miss) with zero debug errors and warnings. Docs only. --- docs/experiments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index 691357d94..a48ae12c0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7430,7 +7430,7 @@ Each scene sends the same 136 rays through a double-precision brute-force CPU te RTX 2060 and WARP each completed 408 comparisons. In fault controls only the custom shader's input changes. Swapping child 0 and 32 addresses changed four results, replaying the previous scene changed 102 and aliasing invalid address high bits changed one. Each fault must alter its designated witness ray. The GTX 1060 with driver 32.0.15.6094 on Windows 10 build 19045.6456 matched all 408 comparisons through DispatchRays. App-local WARP 1.0.22 with Agility SDK 1.620.2 matched all 408 through each DXR path. All three fault witnesses fired in each run. The five-ray and differential checks reported zero D3D12 debug warnings and errors. In-box WARP 10.0.19041.5794 reports no DXR and skips these checks. -On Windows 11 build 26300.9974, the Intel Arc 140T (32.0.101.8132) matched all 408 comparisons through its inline ray-query backend, 136 per epoch with 96, 43 and 92 hits. The fault controls kept their signature: swapping the child 0 and 32 addresses changed four results at witness 0, replaying the previous scene changed 102 at witness 1, and aliasing the high address bits changed one at witness 31, with zero D3D12 debug errors and warnings. +On Windows 11 build 26300.9974, the Intel Arc 140T (32.0.101.8132) matched all 408 comparisons through its inline ray-query backend, 136 per epoch with 96, 43 and 92 hits. The fault controls kept their signature: swapping the child 0 and 32 addresses changed four results at witness 0, replaying the previous scene changed 102 at witness 1, and aliasing the high address bits changed one at witness 31, with zero D3D12 debug errors and warnings. The five-ray checks in the same command group, `dxr_pipeline_hardware` and `dxr_query_hardware`, returned identical results on this adapter: rays 0 and 3 hit instances 7 and 11 at distance 1, rays 1, 2 and 4 missed, and both runs reported zero D3D12 debug errors and warnings. ```powershell $env:XBOX2WINDOWS_ADAPTER = 'GTX 1060' From edcba82c26fe0549197ebf622908e2f6be572444 Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:01:36 +0800 Subject: [PATCH 139/775] docs: record descriptor heap paging on Intel Xe2 The two-logical-heaps paragraph records the GTX 1060 and in-box WARP words. Add the Intel Arc 140T at 06e2ff78: the same four baseline words, swapped=0 and zero D3D12 debug errors and warnings. Docs only. --- docs/experiments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index 691357d94..e87fa6cb7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6449,7 +6449,7 @@ The original test machine had Windows Graphics Tools installed. A second build i `descriptor_heap_paging` gives two logical heaps three 256-slot pages each and shares a 1,024-slot shader-visible heap between them. The first touches allocate pages in A, B order. Copying two descriptors at logical slot 255 splits each copy at page 256 and allocates each heap's second page. The two copies land at physical slots `255,512` and `511,768`. Both third pages stay unmapped. The page size and allocation order belong to the fixture. It uses the on-demand publication idea in the public XCL paging comparison. [Tracking issue #874](https://github.com/R0Y00/Xbox2Windows/issues/874) · [XCL descriptor paging](https://github.com/ivall/xcl/pull/84) -The Windows 10 22H2 `19045.6456` GTX 1060 6 GB (`32.0.15.6094`) and in-box WARP (`10.0.19041.5794`) both returned `S_OK` for the 1,024-slot heap. The four GPU reads returned `a00100ff,a0010100,b00200ff,b0020100`. The swapped-heap control bound the same shared heap and returned `b00200ff,b0020100,a00100ff,a0010100`. Debug and Release passed with no D3D12 warnings or errors. Tests skip on adapters without Shader Model 6.0. +The Windows 10 22H2 `19045.6456` GTX 1060 6 GB (`32.0.15.6094`) and in-box WARP (`10.0.19041.5794`) both returned `S_OK` for the 1,024-slot heap. The four GPU reads returned `a00100ff,a0010100,b00200ff,b0020100`. The swapped-heap control bound the same shared heap and returned `b00200ff,b0020100,a00100ff,a0010100`. Debug and Release passed with no D3D12 warnings or errors. Tests skip on adapters without Shader Model 6.0. On Windows 11 build 26300.9974, the Intel Arc 140T (device `7d51`, driver 32.0.101.8132) returned the same four baseline words with `swapped=0` and zero D3D12 debug errors and warnings. ```powershell cmake --preset dev From 8a8e7e39e8be4d7ab040b5414ce761d6d8762dfc Mon Sep 17 00:00:00 2001 From: ChazY11 <246129015+ChazY11@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:09:13 +0800 Subject: [PATCH 140/775] docs: record the static-sampler PSO on Intel Xe2 The d3d12x_pso section lists the cases and their checks but no adapter result. Record the Intel Arc 140T run at 06e2ff78: the root signature and the PSO are created (pso_blob_bytes=208, both non-null), the desktop-tagged variant is refused with 0x80070057, and the static sampler decodes to filter=0x15 address=1/3/4 comparison=7 border=2 min_lod=1.5 max_lod=9. Docs only. --- docs/experiments.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 691357d94..e717b7cdb 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5849,6 +5849,8 @@ with a null `pRootSignature` must also return `E_INVALIDARG` and no PSO. Run `ctest --preset dev --no-tests=error -R '^d3d12x_pso_' -V`. +On Windows 11 build 26300.9974, the Intel Arc 140T (device `7d51`, driver 32.0.101.8132) created the root signature and the PSO (`pso_blob_bytes=208`, both non-null) while the desktop-tagged variant was refused with `0x80070057`, and it reported the static sampler as `filter=0x15 address=1/3/4 comparison=7 border=2 min_lod=1.5 max_lod=9`. + This fixture covers creation only. It dispatches no work, binds no descriptor heap and reads nothing back, so it does not establish that a dispatch using this root signature produces correct results. It also makes no console descriptor or vtable claim: the public From 9bb7e5ec542cfbb9f450e0bc423ca8d819d001cc Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 14:09:36 +0100 Subject: [PATCH 141/775] Snapshot failed Queue::Submit entries at the cutoff and complete them on the worker behind the prefix --- src/startup_stubs/xcrdapi.cpp | 108 ++++++++++++++++++++++--- tests/startup_storage_worker_start.cpp | 28 +++++-- 2 files changed, 119 insertions(+), 17 deletions(-) diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 7793aa2bc..c5ba66573 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -78,6 +78,7 @@ struct Entry { u64 value; u64 id = 0; u64 submission_id = 0; + u64 after = 0; // failing: entries the worker must have finished before this one completes }; struct CachedStream { u64 source = 0; @@ -92,6 +93,10 @@ struct QueueWork { std::mutex mutex; std::condition_variable wake; std::deque waiting, submitted; + std::deque failing; // snapshot of waiting entries a Submit could not move, completed in order + struct Unrecorded* deferred_head = nullptr; // snapshot of unrecorded entries, in order; guarded by mutex + struct Unrecorded* deferred_tail = nullptr; + std::mutex completion; // one thread at a time completes snapshot entries, so they stay in order std::condition_variable drained; // signaled when the worker finishes an entry u64 submitted_total = 0; // entries ever moved to `submitted`, guarded by mutex u64 finished_total = 0; // entries the worker has finished running, guarded by mutex @@ -642,6 +647,8 @@ void fail_entry(Object* self, const Entry& entry, const char* reason) noexcept thread_local bool on_queue_worker = false; // Submit from a worker must not wait for itself +void complete_deferred(Object* self, QueueWork* work); + DWORD WINAPI queue_worker(void* parameter) { on_queue_worker = true; @@ -683,6 +690,7 @@ DWORD WINAPI queue_worker(void* parameter) ++work.finished_total; } work.drained.notify_all(); + complete_deferred(self, &work); } } @@ -737,6 +745,8 @@ bool start_worker(Object* self, QueueWork* work) // request only counts as failed. struct Unrecorded { Unrecorded* next; + u64 submission_id; + u64 after; Entry::Type type; Object* array; unsigned index; @@ -773,8 +783,9 @@ void fail_unstarted(Object* self, Entry::Type type, Object* array, unsigned inde // deferred, every later entry until the next Submit is deferred too, even if it could be stored: // the stored entries (`waiting`) are an in-order prefix and the deferred ones an in-order suffix. // Submit handles the prefix first (moves it to the worker, or fails it), then fails the suffix. -// When the prefix runs on the worker, Submit waits for the worker to finish it before it fails the -// suffix, so suffix completions are visible in queue order and see the prefix's failures. After the first allocation failure the rest of the batch fails with E_OUTOFMEMORY even if +// Submit snapshots the failing entries at its cutoff and the worker completes that snapshot right after +// it finishes the prefix, so suffix completions are visible in queue order and see the prefix's failures, +// a later batch cannot be completed by this Submit, and Submit never waits for the prefix. After the first allocation failure the rest of the batch fails with E_OUTOFMEMORY even if // memory has recovered, which is acceptable under out-of-memory and preferable to reordering. bool has_unrecorded(Object* self) { @@ -784,7 +795,7 @@ bool has_unrecorded(Object* self) void defer_unrecorded(Object* self, const Entry& entry) { - auto* node = new (std::nothrow) Unrecorded{nullptr, entry.type, entry.array, entry.index, entry.fence, entry.value}; + auto* node = new (std::nothrow) Unrecorded{nullptr, 0, 0, entry.type, entry.array, entry.index, entry.fence, entry.value}; if (!node) { fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value); return; @@ -844,6 +855,8 @@ void submit(Object* self) return; } bool all_moved = true; + bool snapshot_ok = true; + bool snapshotted = false; u64 prefix_end = 0; { const std::lock_guard guard(work->mutex); @@ -861,18 +874,89 @@ void submit(Object* self) all_moved = false; } prefix_end = work->submitted_total; + // The cutoff: the entries that fail are snapshotted here, under the same lock, so a batch enqueued + // later cannot be completed by this Submit. The snapshot completes on the worker right after it + // finishes the prefix (see complete_deferred), so this call never waits for the prefix. + try { + while (!work->waiting.empty()) { + Entry& entry = work->waiting.front(); + entry.submission_id = submission_id; + entry.after = prefix_end; + work->failing.push_back(std::move(entry)); + work->waiting.pop_front(); + snapshotted = true; + } + } catch (const std::bad_alloc&) { + snapshot_ok = false; + } + if (snapshot_ok) { + Unrecorded* node; + { + const std::lock_guard setup(setup_mutex()); + node = self->unrecorded_head; + self->unrecorded_head = self->unrecorded_tail = nullptr; + } + for (Unrecorded* n = node; n; n = n->next) { + n->submission_id = submission_id; + n->after = prefix_end; + if (!n->next) { + (work->deferred_tail ? work->deferred_tail->next : work->deferred_head) = node; + work->deferred_tail = n; + } + snapshotted = true; + } + } } work->wake.notify_one(); - // Entries completed here (the rest of `waiting`, the suffix) come after the prefix on the worker, so - // they wait until the worker has finished that prefix: a status entry or fence then cannot complete - // ahead of an earlier request, and cannot consume the pending failure before the worker reports it. - // Nothing allocates, and nothing waits when there is nothing to complete here. - if ((!all_moved || has_unrecorded(self)) && !on_queue_worker) { - std::unique_lock lock(work->mutex); - work->drained.wait(lock, [&] { return work->finished_total >= prefix_end; }); + if (!snapshot_ok) { + // Last resort when even the snapshot could not grow: wait for the prefix as before, then fail in order. + if (!on_queue_worker) { + std::unique_lock lock(work->mutex); + work->drained.wait(lock, [&] { return work->finished_total >= prefix_end; }); + } + complete_deferred(self, work); + fail_waiting(self, work); + fail_unrecorded(self); + return; + } + if (snapshotted) complete_deferred(self, work); +} + +// Completes the snapshot entries (failed entries of earlier Submits) whose prefix the worker has finished, +// in Submit order and, within one Submit, stored entries before unrecorded ones. Called by the worker after +// every entry and by Submit, so nothing waits on a calling thread. Nothing allocates. +void complete_deferred(Object* self, QueueWork* work) +{ + const std::lock_guard serial(work->completion); + for (;;) { + Entry entry{}; + Unrecorded* node = nullptr; + { + const std::lock_guard guard(work->mutex); + bool take_entry = !work->failing.empty() && work->failing.front().after <= work->finished_total; + bool take_node = work->deferred_head && work->deferred_head->after <= work->finished_total; + if (take_entry && take_node) { + if (work->failing.front().submission_id <= work->deferred_head->submission_id) take_node = false; + else take_entry = false; + } + if (take_entry) { + entry = std::move(work->failing.front()); + work->failing.pop_front(); + } else if (take_node) { + node = work->deferred_head; + work->deferred_head = node->next; + if (!work->deferred_head) work->deferred_tail = nullptr; + } else { + return; + } + } + if (node) { + fail_unstarted(self, node->type, node->array, node->index, node->fence, node->value); + delete node; + } else { + fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value); + } } - if (!all_moved) fail_waiting(self, work); - fail_unrecorded(self); } // Enqueue only records the entry, whether or not a worker runs; nothing completes before Submit. diff --git a/tests/startup_storage_worker_start.cpp b/tests/startup_storage_worker_start.cpp index 6ebb49511..fad138cb1 100644 --- a/tests/startup_storage_worker_start.cpp +++ b/tests/startup_storage_worker_start.cpp @@ -635,17 +635,35 @@ bool suffix_waits_for_prefix(Fixture& f) HANDLE thread = CreateThread(nullptr, 0, SubmitThread::run, &submitter, 0, nullptr); if (!thread) return fail("cannot start the Submit thread"); const bool held = WaitForSingleObject(hold_entered, completion_timeout_ms) == WAIT_OBJECT_0; - if (held) Sleep(200); // time for a Submit that does not wait to complete the suffix - const bool early = f.complete(q, 0) || suffix_fence.signals != 0; + // Submit snapshots the batch and returns without waiting for the held prefix. + const bool submit_returned = held && WaitForSingleObject(thread, completion_timeout_ms) == WAIT_OBJECT_0; + // A second batch enqueued and submitted while the first prefix is held: its status and fence must + // stay pending, and the first Submit must not have completed them. + HoldFence second_fence; + second_fence.vtable = hold_vtable; + bool early = false; + if (submit_returned) { + reinterpret_cast(q.queue->vtable[5])(q.queue, &second_fence, 3); + f.status_entry(q, 1); + f.submit(q); + Sleep(200); // time for a Submit that completes ahead of the held prefix + early = f.complete(q, 0) || f.complete(q, 1) || suffix_fence.signals != 0 || second_fence.signals != 0; + } SetEvent(hold_release); WaitForSingleObject(thread, completion_timeout_ms); CloseHandle(thread); hold_prefix = false; + if (held && !submit_returned) return fail("Submit waited for the held prefix on the calling thread"); if (!held) return fail("the worker never reached the held prefix fence"); if (early) return fail("a status entry or fence of the failed suffix completed before the held prefix"); - if (!f.complete(q, 0) || prefix_fence.signals != 1 || suffix_fence.signals != 1) - return fail("the prefix and the suffix did not both complete"); - if (prefix_fence.order >= suffix_fence.order) return fail("the suffix fence was signaled before the prefix fence"); + { + const DWORD start = GetTickCount(); + while ((!f.complete(q, 1) || second_fence.signals == 0) && GetTickCount() - start < completion_timeout_ms) Sleep(1); + } + if (!f.complete(q, 0) || prefix_fence.signals != 1 || suffix_fence.signals != 1 || second_fence.signals != 1) + return fail("the prefix, the suffix and the second batch did not all complete"); + if (prefix_fence.order >= suffix_fence.order || suffix_fence.order >= second_fence.order) + return fail("the fences were not signaled in queue order"); } CloseHandle(hold_entered); CloseHandle(hold_release); From aa0e90b210e0131f29ef041c4132db7cbd7f18cb Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Tue, 24 Nov 2026 21:10:34 +0800 Subject: [PATCH 142/775] Handle allocation failure before taking the XApu connection lock --- src/startup_stubs/xapu.cpp | 53 +++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index b2fe3b9cd..c6043a4c1 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -5,9 +5,8 @@ #include "startup_stubs/trap.h" #include "startup_stubs/local_log.h" #include -#include #include -#include +#include // Experimental (docs/startup-runtime.md). With X2W_AUDIO_PERMISSIVE=1 the exports // stand in for the audio command queue; otherwise they trap. Call shapes from the title: @@ -25,31 +24,26 @@ constexpr long hr_ok = 0; constexpr long hr_pointer = static_cast(0x80004003); // E_POINTER constexpr long hr_fail = static_cast(0x80004005); // E_FAIL constexpr long hr_handle = static_cast(0x80070006); // E_HANDLE +constexpr long hr_out_of_memory = static_cast(0x8007000E); // E_OUTOFMEMORY constexpr std::size_t result_size = 0x58; bool permissive() noexcept { return x2w_local::env_on("X2W_AUDIO_PERMISSIVE"); } struct Connection { + Connection* next = nullptr; u64 handle = 0; std::uint64_t pending_results = 0; }; SRWLOCK connection_lock = SRWLOCK_INIT; +Connection* connections = nullptr; u64 next_handle = 0x5841500000000001ULL; -unsigned long long connection_count = 0; bool timer_active = false; -std::vector& connections() -{ - static auto* list = new std::vector(); - return *list; -} - Connection* find_connection(u64 handle) noexcept { - if (!handle) return nullptr; - for (auto& conn : connections()) { - if (conn.handle == handle) return &conn; + for (auto* conn = connections; conn; conn = conn->next) { + if (conn->handle == handle) return conn; } return nullptr; } @@ -75,11 +69,15 @@ extern "C" __declspec(noinline) long XApuConnect(u64 rcx, u64 rdx, u64 r8, u64 r x2w_local::logf("x2w-audio XApuConnect input=[%s] output(before)=[%s] -> E_POINTER", input, output); return hr_pointer; } + auto* conn = new (std::nothrow) Connection; + if (!conn) return hr_out_of_memory; AcquireSRWLockExclusive(&connection_lock); const u64 handle = next_handle++; if (next_handle == 0) next_handle = 0x5841500000000001ULL; - connections().push_back({handle, 0}); - if (connection_count++ == 0) { + conn->handle = handle; + conn->next = connections; + connections = conn; + if (!conn->next) { // The mix worker sleeps for 2 ms between refills. A coarse Windows tick can // stretch that wait beyond the time represented by the queued samples. timer_active = timeBeginPeriod(1) == TIMERR_NOERROR; @@ -165,19 +163,20 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuDisconnect", 2, rcx, rdx, r8, r9, _ReturnAddress()); AcquireSRWLockExclusive(&connection_lock); - auto& list = connections(); - auto it = std::find_if(list.begin(), list.end(), [rcx](const Connection& conn) { return conn.handle == rcx; }); - if (it != list.end()) { - list.erase(it); - if (connection_count && --connection_count == 0 && timer_active) { - timeEndPeriod(1); - timer_active = false; - } - ReleaseSRWLockExclusive(&connection_lock); - x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> S_OK", rcx); - return hr_ok; + Connection** slot = &connections; + while (*slot && (*slot)->handle != rcx) slot = &(*slot)->next; + Connection* conn = *slot; + if (conn) *slot = conn->next; + if (conn && !connections && timer_active) { + timeEndPeriod(1); + timer_active = false; } ReleaseSRWLockExclusive(&connection_lock); - x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> E_HANDLE", rcx); - return hr_handle; + if (!conn) { + x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> E_HANDLE", rcx); + return hr_handle; + } + delete conn; + x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> S_OK", rcx); + return hr_ok; } From 1b7b2c06be0586be5fb8c53bfdf4fc8500fc3c05 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 20:51:26 +0800 Subject: [PATCH 143/775] shader: lower gfx1030 image atomic integer min and max --- CMakeLists.txt | 5 ++ README.md | 2 +- docs/experiments.md | 22 ++++++--- tests/compute_check.cpp | 16 ++++++- tests/compute_store_check.py | 93 ++++++++++++++++++++++++++---------- tools/compute_store_aot.py | 26 ++++++---- 6 files changed, 119 insertions(+), 45 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 37c1e7091..6e072e842 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5791,6 +5791,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mimg_atomic_integer_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mimg_atomic_integer_${adapter}.txt") + add_test(NAME compute_store_aot_mimg_atomic_minmax_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mimg-atomic-minmax "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_mimg_atomic_minmax_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mimg_atomic_minmax_${adapter}.txt") add_test(NAME compute_store_aot_ds_route_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-ds-route "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 443b53f57..690dea9c4 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 image queries | Lower [2D mip dimensions and level count](docs/experiments.md#gfx1030-2d-image-resource-queries) for `image_get_resinfo`. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_resinfo_'` | | gfx1030 MSAA image load | Lower [`image_msaa_load` for 4× `R32_UINT` 2D input](docs/experiments.md#gfx1030-4-sample-image-load). Compare the four samples per pixel and the untouched UAV words against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_msaa_'` | | gfx1030 image stores | Lower [typed RGBA32 and packed RGBA8 2D writes](docs/experiments.md#gfx1030-2d-image-stores), including fixed explicit mip levels and sparse `dmask` values. Compare all mip levels against a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_store_'` | -| gfx1030 image atomics | Lower [non-returning add, subtract and bitwise atomics on scalar 2D UAVs](docs/experiments.md#gfx1030-2d-integer-image-atomics). Compare all mips and include a contended add case. | `ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_mimg_atomic_integer_'` | +| gfx1030 image atomics | Lower [non-returning add, subtract, bitwise and integer min/max atomics on scalar 2D UAVs](docs/experiments.md#gfx1030-2d-integer-image-atomics). Compare all mips, including a contended add and signedness controls. | `ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_mimg_atomic_(integer|minmax)_'` | | gfx1030 formatted D16 UINT reads | Lower [indexed `buffer_load_format_d16_*` with caller-declared RGBA16 UINT](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-reads) and verify packed channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_load_format_d16_'` | | gfx1030 raw D16 reads | Lower [indexed D16 byte and short MUBUF loads](docs/experiments.md#indexed-gfx1030-raw-d16-reads) and verify that the other VGPR half stays unchanged. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_d16_'` | | gfx1030 formatted UINT buffer reads | Lower [indexed `buffer_load_format_*` with caller-declared RGBA32 UINT](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-reads) and verify one to four channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_format_'` | diff --git a/docs/experiments.md b/docs/experiments.md index 2dd9cc43c..09e80b2a0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3421,7 +3421,7 @@ ctest --preset dev --no-tests=error -R '^compute_store_aot_mimg_store_(packed_)? The compute store profile lowers one unguarded 32-bit `image_atomic_*` instruction per `gfx1030` shader, with `glc` clear, one 32-bit data VGPR, a contiguous pair of 32-bit X/Y coordinate VGPRs, and optional `unorm`. -The caller supplies in-bounds coordinates and declares a scalar `R32_UINT` +The caller supplies in-bounds coordinates and declares a scalar integer 2D image with identity channel selectors and binds its matching UAV to `u0` at mip 0. The eight resource words must be loaded from the declared table offset and ready at issue. The translator tracks the descriptor's provenance. @@ -3434,20 +3434,27 @@ this profile. See sections 8.2 and 12.16 of the |---|---| | `add`, `sub` | `InterlockedAdd`, `R32_UINT`, negate the subtract operand modulo 2^32 | | `and`, `or`, `xor` | Matching `Interlocked` bitwise intrinsic, `R32_UINT` | +| `smin`, `smax` | Signed `InterlockedMin` or `InterlockedMax`, `R32_SINT`, reinterpret the operand with `asint` | +| `umin`, `umax` | Unsigned `InterlockedMin` or `InterlockedMax`, `R32_UINT` | `DMASK` is `0x1`. The [format support query](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_format_support2) gates the typed atomic operations for each view. An unavailable capability -returns 77. The GPU fixture compares 336 words over all three mips of a +returns 77. Min/max has its own suite and checks the signed or unsigned +min/max capability for each dispatch; it does not gate arithmetic or bitwise +tests. The GPU fixture compares 336 words over all three mips of a 32x8 texture per case, including untouched words. One- and two-group draws exercise high-bit inputs, arithmetic wraparound and two lanes adding to each texel in the contended add case. Lowering subtract as add must fail -first at mip 0, word 32. The test records the five forms only after all -positive and negative dispatch checks complete. +first at mip 0, word 32. The min/max fixture checks both same-sign and +opposite-sign pairs with an independent CPU comparison. For each form, +switching the comparison's signedness and binding the matching UAV must fail +first at mip 0, word 33. Only a complete suite records coverage. Returning +atomics, exchange, compare-exchange, counters and float atomics are not lowered. The LLVM 15 test assembles, disassembles and translates the cases through the -synthetic-container CLI. The standalone compile mode checks the generated -`cs_6_0` shaders and the subtract mutation without adapter access. The GPU +synthetic-container CLI. The standalone compile modes check the generated +`cs_6_0` shaders and their mutations without adapter access. The GPU tests are the translated DXIL comparison against the CPU reference. Run these serially after coordinating adapter access. @@ -3456,8 +3463,9 @@ $Dxc = (Get-Command dxc -ErrorAction Stop).Source $env:TMP = (Resolve-Path out).Path $env:TEMP = $env:TMP python -B tests/compute_store_check.py compile-mimg-atomic-integer $Dxc +python -B tests/compute_store_check.py compile-mimg-atomic-minmax $Dxc cmake --build --preset dev --target offscreen_check -ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_mimg_atomic_integer_(warp|hardware)$' -V +ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_mimg_atomic_(integer|minmax)_(warp|hardware)$' -V ``` ```bash diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index 752ff7119..0d7533398 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -26,7 +26,11 @@ constexpr UINT uavs = 13, srvs = 21; // carries raw texels, one word each for RGBA8 and scalar R32, or four for RGBA32. constexpr UINT texture_rgba8_flag = 1u << 24; constexpr UINT texture_atomic_uint_flag = 1u << 25; -constexpr UINT texture_format_mask = texture_rgba8_flag | texture_atomic_uint_flag; +constexpr UINT texture_atomic_sint_minmax_flag = 1u << 26; +constexpr UINT texture_atomic_uint_minmax_flag = 1u << 27; +constexpr UINT texture_atomic_mask = texture_atomic_uint_flag | texture_atomic_sint_minmax_flag | + texture_atomic_uint_minmax_flag; +constexpr UINT texture_format_mask = texture_rgba8_flag | texture_atomic_mask; constexpr UINT texture_width = 32, texture_height = 8, texture_channels = 4; constexpr UINT texture_mip_levels = 3; } @@ -424,6 +428,14 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co required = D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS; break; + case texture_atomic_sint_minmax_flag: + format = DXGI_FORMAT_R32_SINT; + required = D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX; + break; + case texture_atomic_uint_minmax_flag: + format = DXGI_FORMAT_R32_UINT; + required = D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX; + break; default: throw std::runtime_error("Invalid compute image store format selector"); } const UINT words_per_texel = selector ? 1 : texture_channels; @@ -433,7 +445,7 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co source.read(reinterpret_cast(initial.data()), all_words * sizeof(UINT)); source.read(reinterpret_cast(expected.data()), all_words * sizeof(UINT)); if (!source || source.peek() != std::char_traits::eof() || !groups || groups > 2 || mip >= texture_mip_levels - || (selector == texture_atomic_uint_flag && mip != 0)) + || ((selector & texture_atomic_mask) && mip != 0)) throw std::runtime_error("Invalid compute image store reference"); D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index 3a2a21ce2..89335c20b 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -3331,10 +3331,12 @@ def binary(directory, assembler, objcopy, library): gfx1030_binary(directory, assembler, objcopy, library, [(name, lines, MIMG_BINDING) for name, _, _, _, _, lines in mimg_resinfo_cases()], "image_get_resinfo", group=(8, 8, 1)) - mimg_atomic_controls() - gfx1030_binary(directory, assembler, objcopy, library, - [(f"image_atomic_{name}", lines, binding) for name, _, lines, binding in mimg_atomic_cases()], - "image_atomic_", group=MIMG_STORE_GROUP) + for minmax in (False, True): + mimg_atomic_controls(minmax=minmax) + gfx1030_binary(directory, assembler, objcopy, library, + [(f"image_atomic_{name}", lines, binding) + for name, _, lines, binding in mimg_atomic_cases(minmax=minmax)], + "image_atomic_", group=MIMG_STORE_GROUP) mimg_store_controls() gfx1030_binary(directory, assembler, objcopy, library, [(name, lines, binding) for name, _, _, lines, binding in mimg_store_cases()], @@ -4800,13 +4802,16 @@ def mimg_resinfo_draw(directory, compiler, renderer, backend): MIMG_ATOMIC_UINT_FLAG = 1 << 25 +MIMG_ATOMIC_MINMAX_FLAGS = {"s": 1 << 26, "u": 1 << 27} +MIMG_ATOMIC_MINMAX_OPS = ("smin", "smax", "umin", "umax") MIMG_ATOMIC_BEFORE = (0xfffffff0, 0x7ffffff0, 0x20, 0x80000000) MIMG_ATOMIC_VALUE = 0x80000011 -def mimg_atomic_cases(): - binding = MIMG_STORE_BINDING | {"image_uav_mip": 0, "image_format": "R32_UINT"} - for op in ("add", "sub", "and", "or", "xor"): +def mimg_atomic_cases(*, minmax=False): + for op in MIMG_ATOMIC_MINMAX_OPS if minmax else ("add", "sub", "and", "or", "xor"): + image_format = "R32_SINT" if op in ("smin", "smax") else "R32_UINT" + binding = MIMG_STORE_BINDING | {"image_uav_mip": 0, "image_format": image_format} for contended in ((False, True) if op == "add" else (False,)): lines = ["s_mov_b32 s12, s7", "s_mov_b32 s13, 0", "s_load_dwordx8 s[24:31], s[12:13], 0x40", @@ -4822,9 +4827,10 @@ def mimg_atomic_cases(): yield op + ("_contended" if contended else ""), contended, lines, binding -def mimg_atomic_controls(): - cases = {op: (lines, binding) for op, _, lines, binding in mimg_atomic_cases()} - lines, binding = cases["add"] +def mimg_atomic_controls(*, minmax=False): + cases = {op: (lines, binding) for op, _, lines, binding in mimg_atomic_cases(minmax=minmax)} + base_op = "smin" if minmax else "add" + lines, binding = cases[base_op] instruction = lines[-3] for changed, diagnostic in ( (instruction.replace("dmask:0x1", "dmask:0xf"), "Unverified image atomic data range or mask"), @@ -4849,25 +4855,34 @@ def mimg_atomic_controls(): rejects("Invalid image UAV binding", aot.lower, lines, MIMG_STORE_GROUP, **(binding | {"image_uav_mip": 1})) srv_binding = {key: value for key, value in binding.items() if key != "image_uav_mip"} - rejects("Unsupported image atomic target or binding", aot.lower, lines, MIMG_STORE_GROUP, + rejects("Invalid or overlapping image descriptor binding" if minmax else "Unsupported image atomic target or binding", + aot.lower, lines, MIMG_STORE_GROUP, **(srv_binding | {"descriptor_offset": MIMG_BINDING["descriptor_offset"]})) msaa = "image_msaa_load v[14:17], v[8:10], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm" rejects("requires an unguarded R32_UINT MSAA binding", aot.lower, variant(lines, (instruction, msaa)), MIMG_STORE_GROUP, **binding) rejects("Invalid image UAV binding", aot.lower, lines, MIMG_STORE_GROUP, **(binding | {"cpu": "gfx1013"})) - rejects("Invalid image UAV binding", aot.lower, lines, MIMG_STORE_GROUP, - **(binding | {"image_format": "R32_SINT"})) - for op in ("swap", "cmpswap", "smin", "smax", "umin", "umax", "inc", "dec", "fcmpswap", "fmin", "fmax"): + for case, case_binding in cases.values(): + wrong_format = "R32_UINT" if case_binding["image_format"] == "R32_SINT" else "R32_SINT" + rejects("Unsupported image atomic target or binding", aot.lower, case, MIMG_STORE_GROUP, + **(case_binding | {"image_format": wrong_format})) + for op in ("swap", "cmpswap", "inc", "dec", "fcmpswap", "fmin", "fmax"): rejects("Unsupported compute instruction", aot.lower, - variant(lines, ("image_atomic_add", "image_atomic_" + op)), MIMG_STORE_GROUP, **binding) + variant(lines, ("image_atomic_" + base_op, "image_atomic_" + op)), MIMG_STORE_GROUP, **binding) rejects("Unsupported image store target", aot.lower, - variant(lines, ("image_atomic_add", "image_store")), MIMG_STORE_GROUP, **binding) + variant(lines, ("image_atomic_" + base_op, "image_store")), MIMG_STORE_GROUP, **binding) def mimg_atomic_reference(op, contended, groups): value = MIMG_ATOMIC_VALUE - update = {"add": lambda old: old + value, "sub": lambda old: old - value, - "and": lambda old: old & value, "or": lambda old: old | value, "xor": lambda old: old ^ value}[op] + if op in MIMG_ATOMIC_MINMAX_OPS: + # Flipping the sign bit maps two's-complement order to unsigned order. + key = (lambda word: word ^ 0x80000000) if op[0] == "s" else None + choose = min if op[1:] == "min" else max + update = lambda old: choose(old, value, key=key) + else: + update = {"add": lambda old: old + value, "sub": lambda old: old - value, + "and": lambda old: old & value, "or": lambda old: old | value, "xor": lambda old: old ^ value}[op] initial, expected = [], [] for level in range(3): for y in range(TEXTURE_HEIGHT >> level): @@ -4884,42 +4899,68 @@ def mimg_atomic_reference(op, contended, groups): return initial, expected -def mimg_atomic_integer(directory, compiler, renderer=None, backend=None): - mimg_atomic_controls() +def mimg_atomic_integer(directory, compiler, renderer=None, backend=None, *, minmax=False): + mimg_atomic_controls(minmax=minmax) record_path = os.environ.get("FORM_COVERAGE_RECORD") if renderer else None record = Path(record_path) if record_path else None if record: record.unlink(missing_ok=True) completed = set() - for name, contended, lines, binding in mimg_atomic_cases(): + for name, contended, lines, binding in mimg_atomic_cases(minmax=minmax): src, cso, case = (directory / f"image_atomic_{name}.{ext}" for ext in ("hlsl", "cso", "case")) code = aot.lower(lines, MIMG_STORE_GROUP, **binding) src.write_text(code, encoding="ascii") compile_shader = [compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src] subprocess.run(compile_shader, check=True) op = name.removesuffix("_contended") + flag = MIMG_ATOMIC_MINMAX_FLAGS[op[0]] if minmax else MIMG_ATOMIC_UINT_FLAG for groups in (1, 2): initial, expected = mimg_atomic_reference(op, contended, groups) assert len(initial) == len(expected) == 336 and initial != expected if renderer: - dispatch = groups | MIMG_ATOMIC_UINT_FLAG + dispatch = groups | flag case.write_bytes(struct.pack("<674I", dispatch, 0, *initial, *expected)) run = [renderer, backend, "--compute-texture-store-case", cso, case] print(f"image_atomic_{name} groups={groups}", flush=True) result = subprocess.run(run) if result.returncode: return result.returncode + mutant = None if op == "sub": correct, wrong = f"(0u - {MIMG_ATOMIC_VALUE:#010x}u)", f"{MIMG_ATOMIC_VALUE:#010x}u" mismatch = "mip=0 word=32 expected=7fffffdf actual=80000001" + control = "wrong atomic operand" assert code.count(correct) == 1 - src.write_text(code.replace(correct, wrong), encoding="ascii") + mutant = code.replace(correct, wrong) + elif minmax: + signed = op[0] == "s" + other = "u" if signed else "s" + decl, wrong_decl = ("int", "uint") if signed else ("uint", "int") + value = f"{MIMG_ATOMIC_VALUE:#010x}u" + correct, wrong = (f"asint({value})", value) if signed else (value, f"asint({value})") + assert code.count(f"RWTexture2D<{decl}>") == code.count(f", {correct});") == 1 + mutant = code.replace(f"RWTexture2D<{decl}>", f"RWTexture2D<{wrong_decl}>").replace( + f", {correct});", f", {wrong});") + _, wrong_expected = mimg_atomic_reference(other + op[1:], contended, groups) + first = next(i for i, (a, b) in enumerate(zip(expected, wrong_expected, strict=True)) if a != b) + assert first == TEXTURE_WIDTH + 1 + mismatch = f"mip=0 word={first} expected={expected[first]:08x} actual={wrong_expected[first]:08x}" + control = "wrong atomic signedness" + if renderer: + dispatch = groups | MIMG_ATOMIC_MINMAX_FLAGS[other] + case.write_bytes(struct.pack("<674I", dispatch, 0, *initial, *expected)) + if mutant is not None: + src.write_text(mutant, encoding="ascii") subprocess.run(compile_shader, check=True) if renderer: bad = subprocess.run(run, capture_output=True, text=True) + if minmax and bad.returncode == 77: + print(bad.stdout, end="") + print(bad.stderr, end="", file=sys.stderr) + return 77 if bad.returncode != 1 or mismatch not in bad.stderr: - raise AssertionError(f"{name}: wrong atomic operand escaped detection\n{bad.stderr}") - print(f"{name} wrong atomic operand: {bad.stderr}", end="") + raise AssertionError(f"{name}: {control} escaped detection\n{bad.stderr}") + print(f"{name} {control}: {bad.stderr}", end="") completed.add(f"image_atomic_{op}") if record: record.parent.mkdir(parents=True, exist_ok=True) @@ -5606,6 +5647,8 @@ def draw(directory, compiler, renderer, backend, cases=None): "draw-mimg-store": mimg_store_draw, "compile-mimg-atomic-integer": lambda d, compiler: mimg_atomic_integer(d, compiler), "draw-mimg-atomic-integer": mimg_atomic_integer, + "compile-mimg-atomic-minmax": lambda d, compiler: mimg_atomic_integer(d, compiler, minmax=True), + "draw-mimg-atomic-minmax": lambda d, *a: mimg_atomic_integer(d, *a, minmax=True), "draw-mimg-packed-store": lambda d, *a: mimg_store_draw(d, *a, packed=True), "draw-ds-route": ds_draw, "draw-lds-qword": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_QWORD_CASES), diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index 5b94dfdf8..256b1ccc8 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -99,7 +99,8 @@ "swap": "Exchange", "cmpswap": "CompareExchange", } -IMAGE_ATOMIC_OPS = "add|sub|and|or|xor" +IMAGE_ATOMIC_OPS = "add|sub|and|or|xor|smin|smax|umin|umax" +IMAGE_ATOMIC_TYPES = {"R32_UINT": "uint", "R32_SINT": "int"} def checked_group(group): @@ -212,7 +213,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N the caller's statement of the image format inside it. The image binds to t0 for loads or u0 for writes, where image_uav_mip selects the writable subresource and replaces descriptor_offset. R32_UINT selects the 4-sample Texture2DMS profile for an SRV or the - non-returning 2D integer atomic profile for a UAV. + non-returning 2D integer atomic profile for a UAV. R32_SINT is UAV-only + and selects signed min/max. """ dims = checked_group(group) if cpu not in ("gfx1013", "gfx1030"): @@ -224,11 +226,11 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N image_msaa = not image_output and image_format == "R32_UINT" if image_msaa and cpu != "gfx1030": raise ValueError("The R32_UINT MSAA image binding requires gfx1030") - image_atomic = image_output and image_format == "R32_UINT" + image_atomic_type = IMAGE_ATOMIC_TYPES.get(image_format) if image_output else None if image_output: if (cpu != "gfx1030" or descriptor_offset is not None or stride is not None - or image_descriptor is None or (image_format not in IMAGE_FORMATS and not image_atomic) - or (image_atomic and image_uav_mip != 0) + or image_descriptor is None or (image_format not in IMAGE_FORMATS and not image_atomic_type) + or (image_atomic_type and image_uav_mip != 0) or not 0 <= image_uav_mip <= 15): raise ValueError("Invalid image UAV binding") descriptor_bindings = {} @@ -255,7 +257,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unsupported formatted source binding") if image_descriptor is not None or image_format is not None: # The 8-dword image descriptor occupies two 16-byte slots. - if (not (image_format in IMAGE_FORMATS or image_msaa or image_atomic) + if (not (image_format in IMAGE_FORMATS or image_msaa or image_atomic_type) or image_descriptor is None or source_descriptor is not None or not 0 <= image_descriptor < 1 << 20 or image_descriptor % 4 or any(image_descriptor + half in descriptor_bindings for half in (0, 16)) @@ -1229,7 +1231,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N r"v\[(?P\d+):(?P\d+)\], s\[(?P\d+):(?P\d+)\] " r"dmask:0x(?P[0-9a-f]+) dim:SQ_RSRC_IMG_2D(?: unorm)?", line): op = m["op"] - if not image_atomic or guard_span is not None or stores: + signed = op in ("smin", "smax") + if image_atomic_type != ("int" if signed else "uint") or guard_span is not None or stores: raise ValueError("Unsupported image atomic target or binding") data = int(m["data"]) if int(m["mask"], 16) != 1 or data > 255: @@ -1250,6 +1253,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N value = hlsl_word(source) if op == "sub": value = f"(0u - {value})" + elif signed: + value = f"asint({value})" stores.append(f" Interlocked{MUBUF_ATOMIC_METHODS[op]}({destination}, {value});") elif m := re.fullmatch(r"image_(?Pload|store|get_resinfo)(?P_mip)?(?P_pck(?:_sgn)?)? " r"(?Pv\d+|v\[\d+:\d+\]), (?Pv\d+|v\[\d+:\d+\]), " @@ -1535,7 +1540,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N local = ", uint3 local : SV_GroupThreadID" # Helpers are selected from the final body, so a float ALU result used only by a DS step still gets its definition. cbuffer += "".join(text for name, text in F32_HELPERS.items() if f"f32_{name}(" in body) - uav = f"RWTexture2D<{'uint' if image_atomic else 'uint4'}>" if image_output else "RWByteAddressBuffer" + uav = f"RWTexture2D<{image_atomic_type or 'uint4'}>" if image_output else "RWByteAddressBuffer" return (f"{cbuffer}{uav} outputData : register(u0);\n[numthreads({dims[0]},{dims[1]},{dims[2]})]\n" f"void main(uint3 tid : SV_DispatchThreadID{local}) {{\n{body}\n}}\n") @@ -1569,8 +1574,9 @@ def main(): help="Table byte offset of the 8-dword image descriptor bound to t0 or u0") parser.add_argument("--image-uav-mip", type=int, help="Bind the image to u0 at this mip instead of binding a raw output descriptor") - parser.add_argument("--image-format", choices=sorted(IMAGE_FORMATS.keys() | {"R32_UINT"}), - help="Caller-declared image format (R32_UINT selects MSAA for an SRV or atomics for a UAV)") + parser.add_argument("--image-format", choices=sorted(IMAGE_FORMATS.keys() | IMAGE_ATOMIC_TYPES.keys()), + help="Caller-declared image format (R32_UINT for MSAA SRVs or atomic UAVs, " + "R32_SINT for signed min/max UAVs)") args = parser.parse_args() if (args.descriptor_offset is None) == (args.image_uav_mip is None): parser.error("Choose either --descriptor-offset or --image-uav-mip") From 2993c12c7826026f670d3d44a9be30a36738d3e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 16:12:06 +0300 Subject: [PATCH 144/775] startup: check the placement publish lock and width src/startup_stubs/placement_publish.h adds a slot-133 buffer to the resource records and to the start index of its placement group, and widens the group's max_width. Binding lookup reads the same maps under note_lock in shared mode and starts its search at the address minus max_width plus one. The only direct check, startup_placement_alloc, fails allocations and checks the rollback, but it adds one record whose width is the largest and checks the lock only after the call returns. Single-point mutants that drop the lock guard, take the guard in shared mode, or assign max_width from the new record instead of keeping the maximum left it, startup_placed_vertex_warp and xmem_page_runs_device_warp passing. startup_placement_publish includes the header without a device. It publishes four records of 1 MiB, 128 KiB, 4 MiB and 256 KiB, probes the lock from the records accessor and from the record copy made under it, and checks the hand-written widths 0x100000, 0x100000, 0x400000 and 0x400000 with each record and index entry. Each of the three mutants now fails it. The startup_placement_publish_shrink_control run expects the narrower width after the second record and must fail. --- CMakeLists.txt | 8 ++ docs/experiments.md | 2 +- tests/startup_placement_publish_check.cpp | 89 +++++++++++++++++++++++ 3 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 tests/startup_placement_publish_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index d86494067..fdf862e39 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -333,6 +333,14 @@ add_executable(startup_placement_alloc tests/startup_placement_alloc.cpp) target_compile_features(startup_placement_alloc PRIVATE cxx_std_17) target_include_directories(startup_placement_alloc PRIVATE src) add_test(NAME startup_placement_alloc COMMAND startup_placement_alloc) +# The same registration under the lock held exclusively, and max_width kept at the widest record +# (src/startup_stubs/placement_publish.h). The mutated run is the negative control. +add_executable(startup_placement_publish_check tests/startup_placement_publish_check.cpp) +target_compile_features(startup_placement_publish_check PRIVATE cxx_std_17) +target_include_directories(startup_placement_publish_check PRIVATE src) +add_test(NAME startup_placement_publish COMMAND startup_placement_publish_check) +add_test(NAME startup_placement_publish_shrink_control COMMAND startup_placement_publish_check --mutate shrink) +set_tests_properties(startup_placement_publish_shrink_control PROPERTIES WILL_FAIL TRUE) add_executable(startup_storage_file_range tests/startup_storage_file_range.cpp) target_compile_features(startup_storage_file_range PRIVATE cxx_std_17) target_include_directories(startup_storage_file_range PRIVATE src) diff --git a/docs/experiments.md b/docs/experiments.md index 691357d94..2071546b0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9901,7 +9901,7 @@ cmake --build --preset release --target startup_stream_consumer startup_placemen ctest --preset release --no-tests=error --output-on-failure -R '^startup_(placement_alloc|placed_vertex_)' ``` -`startup_placement_alloc` fails each allocation made while adding a second buffer. It checks that the operation returns `E_OUTOFMEMORY`, the existing resource and index remain intact, the lock can be reacquired, and registration at the same address succeeds on retry. +`startup_placement_alloc` fails each allocation made while adding a second buffer. It checks that the operation returns `E_OUTOFMEMORY`, the existing resource and index remain intact, the lock can be reacquired, and registration at the same address succeeds on retry. `ctest --preset dev --no-tests=error -R '^startup_placement_publish(_shrink_control)?$' -V` checks `src/startup_stubs/placement_publish.h` without a device: each record is copied in while the lock is held exclusively, and the group's `max_width` stays at the widest record when a narrower one follows, because lookup starts at the address minus `max_width` plus one. The control expects the narrower width and must fail. ### Nine-mip BC5/BC7 tile queries diff --git a/tests/startup_placement_publish_check.cpp b/tests/startup_placement_publish_check.cpp new file mode 100644 index 000000000..99e3be84a --- /dev/null +++ b/tests/startup_placement_publish_check.cpp @@ -0,0 +1,89 @@ +// publish_placement (src/startup_stubs/placement_publish.h) without a device. The record is read and +// written while the caller's lock is held exclusively, because binding lookup reads the same maps +// under that lock in shared mode. max_width stays the widest record published in the group, because +// lookup starts its search at address - max_width + 1. +#include "startup_stubs/placement_publish.h" + +#include +#include +#include + +namespace { +SRWLOCK lock = SRWLOCK_INIT; +int probes; +int not_exclusive; // probes that could take the lock in shared mode + +void probe() +{ + ++probes; + if (TryAcquireSRWLockShared(&lock)) { + ReleaseSRWLockShared(&lock); + ++not_exclusive; + } +} + +// The registry copies the record into its node, so the copy shows whether the lock is held then. +struct Record { + std::uint64_t bytes; + explicit Record(std::uint64_t value) : bytes(value) {} + Record(const Record& other) : bytes(other.bytes) { probe(); } + Record& operator=(const Record&) = default; +}; + +int fail(int code, const char* what) +{ + std::fprintf(stderr, "placement publish: %s\n", what); + return code; +} +} // namespace + +int main(int argc, char** argv) +{ + // The control expects the narrower second record to shrink the window and must fail. + const bool shrink = argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "shrink") == 0; + if (argc != 1 && !shrink) return fail(64, "usage: startup_placement_publish_check [--mutate shrink]"); + + using Key = unsigned; + std::unordered_map records; + std::multimap by_start; + std::uint64_t max_width = 0; + + // Widths of the large group (above 64 KiB). Expected max_width after each one: + // 1 MiB -> 0x100000; 128 KiB keeps 0x100000; 4 MiB -> 0x400000; 256 KiB keeps 0x400000. + // With 0x20000 after the second record, a lookup of the last byte of the first record + // (0x100FFFFF) would start at 0x100E0000 and miss the record at 0x10000000. + struct Step { Key owner; std::uint64_t start, bytes, expected_width; }; + const Step steps[] = { + {1, 0x10000000, 0x100000, 0x100000}, + {2, 0x20000000, 0x20000, shrink ? 0x20000u : 0x100000u}, + {3, 0x30000000, 0x400000, 0x400000}, + {4, 0x40000000, 0x40000, 0x400000}, + }; + int published = 0; + for (const Step& step : steps) { + const Record record(step.bytes); + probes = not_exclusive = 0; + const HRESULT hr = x2w_startup::publish_placement(lock, [&]() -> auto& { probe(); return records; }, + by_start, max_width, step.owner, step.start, record); + ++published; + if (hr != S_OK) return fail(1, "a new owner was not published"); + // One probe when the records are fetched and one when the new record is copied in. + if (probes != 2) return fail(2, "the records were not fetched once and the record copied once"); + if (not_exclusive) return fail(3, "the record was published without the lock held exclusively"); + if (!TryAcquireSRWLockExclusive(&lock)) return fail(4, "the lock is still held after the call"); + ReleaseSRWLockExclusive(&lock); + if (max_width != step.expected_width) { + std::fprintf(stderr, "after owner %u: max_width 0x%llx, expected 0x%llx\n", step.owner, + static_cast(max_width), + static_cast(step.expected_width)); + return fail(5, "max_width is not the widest record published"); + } + if (records.size() != static_cast(published) || records.at(step.owner).bytes != step.bytes) + return fail(6, "the record was not stored under its owner"); + if (by_start.size() != static_cast(published) || by_start.count(step.start) != 1 || + by_start.find(step.start)->second != step.owner) + return fail(7, "the index does not map the start to its owner"); + } + std::printf("placement publish: 4 records under the exclusive lock, max_width 0x100000 then 0x400000\n"); + return 0; +} From 04d78f3d93adf5e61a446766565be7a3861289df Mon Sep 17 00:00:00 2001 From: Simsalabim <83839581+SimSalabimse@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:12:24 +0100 Subject: [PATCH 145/775] tests: constant-initialize the TLS value template on MSVC 19.42 A brace list of plain constant expressions puts the same 8 KiB span_word pattern into the TLS template of cpu_tls_value.dll. On 19.42 a thread-local aggregate initialized by a function call, including constexpr make_span(), is dynamic, so the existing template check never saw the array. Refs #1465 --- tests/cpu/tls_value.cpp | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/tests/cpu/tls_value.cpp b/tests/cpu/tls_value.cpp index e64f70b62..67abb6898 100644 --- a/tests/cpu/tls_value.cpp +++ b/tests/cpu/tls_value.cpp @@ -29,6 +29,21 @@ extern "C" __declspec(dllimport) void sink_record(void* module, unsigned reason, constexpr std::uint32_t SPAN_WORDS = 2048; // 8 KiB +// MSVC 19.42 constant-initializes a thread-local aggregate only from a brace list of plain +// constant expressions. An initializer that calls a function, constexpr or not, is dynamic, so +// the 8 KiB pattern never reaches the TLS template (#1465). The same brace-list form was the +// first comparison in #1119. +#define SPAN_WORD(i) (0xA5000000u ^ ((i) * 0x9E3779B1u)) +#define SPAN_WORDS_4(i) SPAN_WORD(i), SPAN_WORD((i) + 1u), SPAN_WORD((i) + 2u), SPAN_WORD((i) + 3u) +#define SPAN_WORDS_16(i) SPAN_WORDS_4(i), SPAN_WORDS_4((i) + 4u), SPAN_WORDS_4((i) + 8u), SPAN_WORDS_4((i) + 12u) +#define SPAN_WORDS_64(i) \ + SPAN_WORDS_16(i), SPAN_WORDS_16((i) + 16u), SPAN_WORDS_16((i) + 32u), SPAN_WORDS_16((i) + 48u) +#define SPAN_WORDS_256(i) \ + SPAN_WORDS_64(i), SPAN_WORDS_64((i) + 64u), SPAN_WORDS_64((i) + 128u), SPAN_WORDS_64((i) + 192u) +#define SPAN_WORDS_1024(i) \ + SPAN_WORDS_256(i), SPAN_WORDS_256((i) + 256u), SPAN_WORDS_256((i) + 512u), SPAN_WORDS_256((i) + 768u) +#define SPAN_TEMPLATE {{SPAN_WORDS_1024(0u), SPAN_WORDS_1024(1024u)}} + // The template value of g_span[i]; tests/cpu/native_tls_value_check.py computes the same words. constexpr std::uint32_t span_word(std::uint32_t i) { return 0xA5000000u ^ (i * 0x9E3779B1u); } @@ -36,17 +51,20 @@ struct Span { std::uint32_t words[SPAN_WORDS]; }; -constexpr Span make_span() { - Span span{}; - for (std::uint32_t i = 0; i < SPAN_WORDS; ++i) span.words[i] = span_word(i); - return span; +constexpr Span span_template_check = SPAN_TEMPLATE; + +constexpr bool span_template_matches() { + for (std::uint32_t i = 0; i < SPAN_WORDS; ++i) + if (span_template_check.words[i] != span_word(i)) return false; + return true; } +static_assert(span_template_matches(), "the brace list must be span_word(0) through span_word(SPAN_WORDS - 1)"); // Global scope by design: the linker must emit g_tls and g_span in the TLS data // template and the callback addresses in .CRT$XL*. An anonymous namespace would // give them internal linkage and obscure the template in a dumpbin review. __declspec(thread) int g_tls = 7; -__declspec(thread) Span g_span = make_span(); +__declspec(thread) Span g_span = SPAN_TEMPLATE; constexpr unsigned CALLER_TLS = 1; constexpr unsigned CALLER_ENTRY = 2; From d9e27f68544ba60732938fe93bfa007b36a5e87e Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 14:12:32 +0100 Subject: [PATCH 146/775] gfx2hlsl: refuse unrestricted implicit image_sample_c without representable derivatives --- tests/startup_image_sample_c_check.py | 21 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 8 ++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/tests/startup_image_sample_c_check.py b/tests/startup_image_sample_c_check.py index 324d4f5bb..b9a2409c3 100644 --- a/tests/startup_image_sample_c_check.py +++ b/tests/startup_image_sample_c_check.py @@ -323,6 +323,27 @@ def controls(): # 0 and the maximum has no static-sampler equivalent and is refused. check_call(pipeline('c_max0').hlsl_ps(), 'SampleCmpLevelZero', 'v1', 'v2', 'v0') refused('c_max_partial', 'sampler MAX_LOD') + # An unrestricted implicit comparison whose derivatives cannot be represented (exec not proven, or inside a + # block) is refused instead of being sampled at level zero, which would pick a different mip. + for label, setup in (('exec uncertain', lambda st: setattr(st, 'exec_known', False)), + ('inside a block', lambda st: st.blocks.append(None))): + original = G.Stage.image_compare + + def patched(self, ops, mods, how, setup=setup, original=original): + saved = (self.exec_known, list(self.blocks)) + setup(self) + try: + return original(self, ops, mods, how) + finally: + self.exec_known, self.blocks[:] = saved + G.Stage.image_compare = patched + try: + refused('c', 'implicit derivatives') + refused('c_nsa', 'implicit derivatives') + check_call(pipeline('c_max0').hlsl_ps(), 'SampleCmpLevelZero', 'v1', 'v2', 'v0') + finally: + G.Stage.image_compare = original + print('unrestricted implicit comparison refused when %s; proven MAX_LOD 0 kept' % label) assert 'Texture2D r0' in lz.hlsl_ps() and 'srv 0 tex2d table 0 0' in lz.manifest() assert manifest_samplers(lz) == ['smpc 0 0x%x 0x0 0x0 0x0' % (POINT | LESS)], manifest_samplers(lz) print('lz: reference v0 at (v1, v2); NSA reference v3 at (v0, v1); c uses SampleCmp; sampler smpc') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index b0134eb3a..083a9daca 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -796,8 +796,12 @@ def image_compare(self, ops, mods, how): max_lod = (words[1] >> 12) & 0xfff if how == 'c' and max_lod not in (0, 0xfff): raise Unsupported('%s with a sampler MAX_LOD of %#x' % (base, max_lod)) - # Implicit derivatives exist only in a pixel stage, as for image_sample. - if how == 'c' and max_lod and self.exec_known and self.kind == 'ps' and len(self.blocks) == 0: + # Implicit derivatives exist only in a pixel stage with a known exec outside any block, as for image_sample. + # Where they cannot be represented, level zero would silently pick a different mip when the sampler does not + # limit the LOD, so that form is refused; a proven MAX_LOD of 0 is exactly level zero. + if how == 'c' and max_lod: + if not (self.exec_known and self.kind == 'ps' and len(self.blocks) == 0): + raise Unsupported('%s with implicit derivatives that cannot be represented here (unrestricted MAX_LOD)' % base) call = '%s.SampleCmp(%s)' % (tex, args) else: call = '%s.SampleCmpLevelZero(%s)' % (tex, args) From 6edd861d84c27c9b9cd837a8dd2dcb3767fa87d9 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Tue, 24 Nov 2026 21:08:19 +0800 Subject: [PATCH 147/775] shader: lower gfx1030 explicit-gradient pixel sampling --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 5 + README.md | 1 + docs/experiments.md | 30 +++++ tests/pixel_sample_gradient_check.py | 180 +++++++++++++++++++++++++++ tools/pixel_aot.py | 30 ++++- 6 files changed, 242 insertions(+), 5 deletions(-) create mode 100644 tests/pixel_sample_gradient_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index f1c47d01e..3ba392fa8 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -48,6 +48,7 @@ jobs: python3 -B tests/mesh_descriptor_swap_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/mesh_lit_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/pixel_get_lod_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 + python3 -B tests/pixel_sample_gradient_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 llc-15 python3 -B tests/mesh_shadow_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/ffx_dispatch_aot_check.py llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 python3 -B tests/startup_sampler_heap_check.py binary llvm-mc-15 diff --git a/CMakeLists.txt b/CMakeLists.txt index 37c1e7091..1d001a380 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5994,6 +5994,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_sample_offset_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sample_offset_${adapter}.txt") + add_test(NAME pixel_aot_sample_gradient_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_sample_gradient_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_sample_gradient_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sample_gradient_${adapter}.txt") add_test(NAME pixel_aot_three_way_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" three-way "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 443b53f57..788cbf65f 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 formatted UINT buffer writes | Lower [indexed `buffer_store_format_*` with matching caller-declared UINT texels](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-writes) and compare full UAV readback with a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | gfx1030 depth-comparison sampling | Lower [2D comparison samples with and without offsets](docs/experiments.md#gfx1030-2d-comparison-sampling). | `ctest --preset dev --no-tests=error -R '^pixel_aot_compare_sample_' -V` | | gfx1030 pixel sampling offsets | Lower [four 2D sample offset forms](docs/experiments.md#offline-pixel-shader-recompilation) with a known packed XY displacement. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_offset_' -V` | +| gfx1030 explicit-gradient pixel sampling | Lower [four 2D gradient sample forms](docs/experiments.md#offline-pixel-shader-recompilation), including packed binary16 slopes and immediate offsets. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_gradient_' -V` | | Shader census | [Distinguish archive records, header digests and cache-index entries](docs/experiments.md#reporting-shader-census-populations) before choosing a coverage denominator. | `ctest --preset dev --no-tests=error -R "^shader_metadata_census$" -V` | | Shader effect metadata | Inventory the [candidate programs for a named SGD5 effect](docs/experiments.md#candidate-programs-for-a-named-sgd5-effect) using independently located archive ranges. | `ctest --preset dev --no-tests=error -R "^sgd5_effect_candidates$" -V` | | gfx1030 image LOD query | Lower [clamped and raw 2D LOD queries](docs/experiments.md#gfx1030-2d-image-lod-queries) for `image_get_lod` in pixel shaders. | `ctest --preset dev --no-tests=error -R '^pixel_aot_get_lod_'` | diff --git a/docs/experiments.md b/docs/experiments.md index dbcd6b3a3..727c7b81e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5299,6 +5299,36 @@ python3 -B tests/pixel_sample_offset_check.py binary llvm-mc-15 llvm-objcopy-15 ctest --preset dev --no-tests=error -R '^pixel_aot_sample_offset_' -V ``` +The same pixel profile lowers `image_sample_d`, `image_sample_d_o`, +`image_sample_d_g16`, and `image_sample_d_o_g16` to `SampleGrad`. For `gfx1030`, +use `--cpu gfx1030` with wave64 input. Each instruction uses contiguous 2D +addresses and `dmask:0xf`. After the optional packed offset word, the +full-precision address has four gradient words in `du/dx`, `dv/dx`, `du/dy`, +`dv/dy` order, followed by 32-bit UV. G16 uses one packed word per screen axis +instead. Each word holds the binary16 U slope in bits `[15:0]` and the V slope +in `[31:16]`. The lowerer widens both halves exactly before passing the two +vectors to `SampleGrad`. Explicit gradients do not require whole-quad UVs in +the source program. Offset bounds and the integer mip sampling assumption are +the same as for the ordinary offset forms. + +LLVM 15 requires an eight-VGPR tuple in the packed full-precision assembly and +prints only the six or seven active registers on disassembly. The binary +fixture round-trips every mnemonic through the pixel CLI and asks `llc` to +confirm the G16 lane order and its independent 32-bit UVs. The draw fixture +uses the existing two-mip texture to distinguish a nonzero horizontal V or +vertical U slope from zero gradients. It also checks a larger slope against +mip 2 of a four-mip texture and both offset forms against the spatial ramp. +Zero gradients must change the first covered pixel from green to red. Zero +offset must change the ramp's first red value from `0x3d808000` to `0x00000000`. + +```bash +python3 -B tests/pixel_sample_gradient_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 llc-15 +``` + +```powershell +ctest --preset dev --no-tests=error -R '^pixel_aot_sample_gradient_' -j1 -V +``` + Depth-comparison sampling covers one form: `image_sample_c_lz vD, v[a:a+2], ... dmask:0x1 dim:SQ_RSRC_IMG_2D` and its NSA spelling `[vR, vU, vV]`. In RDNA 2 the reference comes before the coordinates. The result lowers to `tex.SampleCmpLevelZero(samp, float2(u, v), reference)` on `Texture2D tex : register(t0)` and `SamplerComparisonState samp : register(s0)`. The four sampler words must still match the caller binding. `comparison_sampler_state()` decodes them, and the generated HLSL names the desktop state it needs in a comment. The compare function comes from word 0 bits 14:12, in the same order as `D3D12_COMPARISON_FUNC` minus one, and the result is `reference OP texel`. One point or bilinear XY filter maps to `D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT` or `..._MIN_MAG_LINEAR_MIP_POINT`. Other values are refused, each with its own message: - X/Y addressing other than `CLAMP_LAST_TEXEL`; - anisotropy, unnormalized coordinates, `MC_COORD_TRUNC` or `FORCE_DEGAMMA`; diff --git a/tests/pixel_sample_gradient_check.py b/tests/pixel_sample_gradient_check.py new file mode 100644 index 000000000..792ae74c3 --- /dev/null +++ b/tests/pixel_sample_gradient_check.py @@ -0,0 +1,180 @@ +"""Exercise the gfx1030 packed 2D SampleGrad forms, including G16.""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import assemble +from pixel_aot_check import envelope, pixel_aot, translate, write_record +from pixel_sample_lod_check import base_prefix, compile_ps, export_tail +from pixel_sample_offset_check import draw, ramp_case, reject + + +# Active address ranges printed by the LLVM 15 disassembler. +FORMS = { + "image_sample_d": (4, 9), + "image_sample_d_o": (3, 9), + "image_sample_d_g16": (6, 9), + "image_sample_d_o_g16": (5, 9), +} +ZERO = ("0", "0", "0", "0") +HORIZONTAL_V = ("0", "-0.25", "0", "0") +VERTICAL_U = ("0", "0", "0.25", "0") +MIP_TWO = ("0", "-0.5", "0", "0") +WAVE64 = "+wavefrontsize64,-wavefrontsize32" + + +def program(op, gradients, *, offset="0x3e01", entry_uv=False): + first, last = FORMS[op] + g16 = op.endswith("_g16") + has_offset = "_o" in op + body = [f"v_mov_b32_e32 v{first}, {offset}"] if has_offset else [] + words = gradients + if g16: + halves = struct.pack("<4e", *map(float, gradients)) + words = tuple(f"{word:#x}" if word else "0" for word in struct.unpack("<2I", halves)) + for register, word in enumerate(words, first + has_offset): + body.append(f"v_mov_b32_e32 v{register}, {word}") + body.append(f"{op} v[12:15], v[{first}:{last}], s[28:35], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D") + prefix = base_prefix() + if entry_uv: + prefix = [line for line in prefix if "exec" not in line] + return prefix + body + export_tail() + + +def check_lowering(): + distinct = ("0.125", "-0.25", "0.5", "1.0") + for op, (first, _) in FORMS.items(): + lines = program(op, distinct, entry_uv=True) + source = translate(lines) + g16 = op.endswith("_g16") + has_offset = "_o" in op + # Decode the call's two gradient vectors back to the defining moves. + first_gradient = next(i for i, line in enumerate(lines) + if line.startswith(f"v_mov_b32_e32 v{first + has_offset},")) + values = [f"alu{i}" for i in range(first_gradient, first_gradient + (2 if g16 else 4))] + if g16: + expected = [(f"widen16(asuint({v}))", f"widen16(asuint({v}) >> 16)") for v in values] + assert f"asfloat({0xb4003000}u)" in source + assert f"asfloat({0x3c003800}u)" in source + else: + expected = [values[:2], values[2:]] + ddx, ddy = [f"float2({u}, {v})" for u, v in expected] + offset = ", int2(1, -2)" if has_offset else "" + assert f"tex.SampleGrad(samp, float2(uv.x, uv.y), {ddx}, {ddy}{offset});" in source, op + + lines = program("image_sample_d", distinct) + for old, new, diagnostic in ( + ("v[4:9]", "v[4:8]", "Descriptor or vector width mismatch"), + ("v[4:9]", "[v4, v5, v6, v7, v8, v9]", "Unsupported instruction"), + ("dmask:0xf", "dmask:0x7", "requires dmask:0xf"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_3D", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D a16", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D d16", "Unsupported instruction"), + ("image_sample_d ", "image_sample_cd ", "Unsupported instruction"), + ("image_sample_d ", "image_sample_d_cl ", "Unsupported instruction"), + ("image_sample_d ", "image_sample_c_d ", "Unsupported instruction"), + ): + reject([line.replace(old, new) for line in lines], diagnostic) + undefined = [line for line in lines if not line.startswith("v_mov_b32_e32 v5,")] + reject(undefined, "Unsupported texture coordinate") + for op in ("image_sample_d", "image_sample_d_g16"): + lines = program(op, distinct) + i = next(i for i, line in enumerate(lines) if line.startswith(op)) + lines.insert(i, "image_sample v[4:7], v[8:9], s[28:35], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D") + reject(lines, "Sample used before vmcnt wait") + bad_offset = program("image_sample_d_o_g16", distinct, offset="0x8") + reject(bad_offset, "outside the DXIL immediate range") + + +def check_g16_codegen(directory, llc): + # Independent check of the immediate gradient words produced by LLVM from + # four distinct scalar derivatives. Keep full float UV to separate G16 from A16. + ir = directory / "gradient-order.ll" + ir.write_text('''target triple = "amdgcn-amd-amdpal" +declare <4 x float> @llvm.amdgcn.image.sample.d.2d.v4f32.f16.f32( + i32 immarg, half, half, half, half, float, float, <8 x i32>, <4 x i32>, i1 immarg, i32 immarg, i32 immarg) +define amdgpu_ps <4 x float> @gradient_order(<8 x i32> inreg %r, <4 x i32> inreg %s, float %u, float %v) { + %value = call <4 x float> @llvm.amdgcn.image.sample.d.2d.v4f32.f16.f32( + i32 15, half 0xH3000, half 0xHB400, half 0xH3800, half 0xH3C00, float %u, float %v, + <8 x i32> %r, <4 x i32> %s, i1 false, i32 0, i32 0) + ret <4 x float> %value +} +''', encoding="ascii") + asm = subprocess.run([llc, "-mcpu=gfx1030", f"-mattr={WAVE64},-nsa-encoding", "-o", "-", ir], + check=True, capture_output=True, text=True).stdout + match = re.search(r"image_sample_d_g16 v\[\d+:\d+\], v\[(\d+):(\d+)\].*dim:SQ_RSRC_IMG_2D", asm) + assert match, asm + assert " a16" not in match[0], match[0] + first, last = map(int, match.groups()) + assert last - first == 3, match[0] + assert f"v_mov_b32_e32 v{first}, 0xb4003000" in asm, asm + assert f"v_mov_b32_e32 v{first + 1}, 0x3c003800" in asm, asm + + +def check_binary(directory, assembler, objcopy, library, llc): + check_g16_codegen(directory, llc) + for op in FORMS: + lines = program(op, ("0", "-0.5", "0", "0"), entry_uv=True) + assembly = lines + if not op.endswith("_g16"): + # The assembler takes the eight-VGPR tuple spelling. The decoded + # instruction lists the six or seven active VGPRs from the same encoding. + first, last = FORMS[op] + assembly = [line.replace(f"v[{first}:{last}]", f"v[{first}:{first + 7}]") + if line.startswith(f"{op} ") else line for line in lines] + code = assemble(directory, assembler, objcopy, assembly, cpu="gfx1030", features=WAVE64) + decoded = pixel_aot.disassemble(code, library, cpu=b"gfx1030", features=WAVE64.encode(), offsets=True) + assert [line for _, line in decoded if line.startswith("image_")] == [ + line for line in lines if line.startswith("image_") + ] + expected = translate(lines) + assert translate(decoded) == expected + archive = directory / "fixture.bin" + archive.write_bytes(envelope(code)) + output = directory / "fixture.hlsl" + subprocess.run([sys.executable, "-B", pixel_aot.__file__, archive, "fixture", "--llvm", library, + "--cpu", "gfx1030", "--texture-sgpr", "20", "--interp-sgpr", "24", + "--sampler-words", "1", "2", "3", "4", "--constant-descriptor", "0x40", + "--output", output], check=True, capture_output=True, text=True) + assert output.read_text(encoding="utf-8") == expected + + +def check_draw(directory, compiler, renderer=None, adapter=None): + # On the 8x8 texture either nonzero slope gives a two-texel footprint + # and selects the green mip. Implicit derivatives and zero slopes give mip zero. + for op in FORMS: + for label, gradients in (("horizontal_v", HORIZONTAL_V), ("vertical_u", VERTICAL_U), ("zero", ZERO)): + shader = compile_ps(compiler, translate(program(op, gradients, entry_uv=True)), directory, f"{op}_{label}") + if renderer is not None: + draw(renderer, adapter, "--check-pixel-quad-lod", shader, mismatch=label == "zero") + # A four-texel footprint selects blue mip 2 of a four-mip texture + # across the full viewport, including pixels outside the partial quad above. + shader = compile_ps(compiler, translate(program(op, MIP_TWO, entry_uv=True)), directory, f"{op}_mip_two") + if renderer is not None: + draw(renderer, adapter, "--check-pixel-mip-clamp", shader, "2") + # Offsets must survive the SampleGrad lowering. Exercise both axes and clamp on a spatial ramp. + case = directory / "gradient-offset.case" + case.write_bytes(ramp_case(1, -2)) + for op in ("image_sample_d_o", "image_sample_d_o_g16"): + for offset in ("0x3e01", "0"): + shader = compile_ps(compiler, translate(program(op, ZERO, offset=offset, entry_uv=True)), + directory, f"{op}_ramp_{offset}") + if renderer is not None: + draw(renderer, adapter, "--check-pixel-case", shader, case, mismatch=offset == "0") + if renderer is not None: + write_record(os.environ.get("FORM_COVERAGE_RECORD")) + + +if __name__ == "__main__": + check_lowering() + if len(sys.argv) > 1: + mode, *args = sys.argv[1:] + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="sample-grad-", dir=out) as tmp: + {"binary": check_binary, "compile": check_draw, "draw": check_draw}[mode](Path(tmp), *args) + print("Four 2D explicit-gradient sample forms checked") diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index cce39cc66..ee82250f2 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -4052,15 +4052,21 @@ def match(pattern): vector[dst] = f"uv.{component}" if mask == "quad" else ("entry_uv", component) else: raise ValueError("Unpaired interpolation") - elif m := match(r"(image_sample(?:_lz|_l|_b)?(?:_o)?) (?:v\[(\d+):(\d+)\]|v(\d+)), " + elif m := match(r"(image_sample(?:(?:_lz|_l|_b)?(?:_o)?|_d(?:_o)?(?:_g16)?)) (?:v\[(\d+):(\d+)\]|v(\d+)), " r"v\[(\d+):(\d+)\], s\[(\d+):(\d+)\], s\[(\d+):(\d+)\] dmask:0x([1-9a-f]) dim:SQ_RSRC_IMG_2D"): op, dst_first, dst_last, dst_single, *rest, dmask_hex = m.groups() dmask = int(dmask_hex, 16) if op != "image_sample" and dmask != 0xf: raise ValueError(f"{op} requires dmask:0xf") - base_op = op.removesuffix("_o") - has_offset = base_op != op - coord_width = (3 if base_op in ("image_sample_l", "image_sample_b") else 2) + has_offset + g16 = op.endswith("_g16") + sample_op = op.removesuffix("_g16") + base_op = sample_op.removesuffix("_o") + has_offset = sample_op != base_op + if base_op == "image_sample_d": + # LLVM disassembly lists only the live address operands. + coord_width = (4 if g16 else 6) + has_offset + else: + coord_width = (3 if base_op in ("image_sample_l", "image_sample_b") else 2) + has_offset channels = ["xyzw"[bit] for bit in range(4) if (dmask >> bit) & 1] if len(channels) == 1: if dst_single is None: @@ -4104,7 +4110,21 @@ def sample_coord(reg): return value return fp_operand(reg, scalar, vector, pending, sample_dest) - if base_op in ("image_sample_lz", "image_sample_l"): + if base_op == "image_sample_d": + u, v = [sample_coord(reg) for reg in coord_regs[-2:]] + # Two coordinate slopes per screen axis, horizontal first. G16 packs + # U in the low half and V in the high half of each gradient word. + if g16: + h, vert = [int_operand(reg, scalar, vector, pending, sample_dest, signed=False) + for reg in coord_regs[:2]] + ddx = f"float2(widen16({h}), widen16({h} >> 16))" + ddy = f"float2(widen16({vert}), widen16({vert} >> 16))" + else: + dudx, dvdx, dudy, dvdy = [sample_coord(reg) for reg in coord_regs[:4]] + ddx = f"float2({dudx}, {dvdx})" + ddy = f"float2({dudy}, {dvdy})" + call = f"SampleGrad(samp, float2({u}, {v}), {ddx}, {ddy}{offset_arg})" + elif base_op in ("image_sample_lz", "image_sample_l"): u, v = [sample_coord(reg) for reg in coord_regs[:2]] lod = sample_coord(coord_regs[2]) if base_op == "image_sample_l" else "0.0f" call = f"SampleLevel(samp, float2({u}, {v}), {lod}{offset_arg})" From 0ae499c73e32d74d215eabd5095c9a248f654ff2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 16:15:40 +0300 Subject: [PATCH 148/775] startup: check the memory SRV report fields src/startup_stubs/memory_srv_report.h formats the line logged for a refused device slot 70 call. startup_memory_srv_report compared it for an acceleration-structure, a buffer and a 2D-array view, but never for a plain 2D view, and its array view used the same value for several fields. startup_address_srv_warp matches the 2D view only with zero fields and accepts any hex address and destination. Nine single-point mutants left both tests passing: mip and plane swapped in the 2D view, its clamp cut to an integer, first slice and count swapped in the array view, only the first qword of an unnamed view copied, the acceleration-structure note added to every unnamed dimension, and the buffer width, first element, address and destination cut to 32 bits. Add four lines to the existing check: an array view and a 2D view with a distinct value in each field and a fractional clamp, a cube-array view printed as raw words without the note, and a buffer wider than 4 GiB with a first element past 2^32. The 2D case uses an address and a destination above 4 GiB. Each of the nine mutants now fails the check. A renamed reason label and the two flags swapped were already caught by both tests. --- docs/startup-runtime.md | 3 ++ tests/startup_memory_srv_report_check.cpp | 63 ++++++++++++++++++++++- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a042aa048..0110a3498 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -792,6 +792,9 @@ Typed element bytes come from the format (1 to 16 bytes). Formats that cannot ba `unsupported_description` and leave the destination descriptor unchanged. Translated draws bind typed views with the format's element size and stride. The refusal reasons are listed in `docs/experiments.md` ("Name the cause of a refused slot 70 call"). +`ctest --preset dev --no-tests=error -R '^startup_memory_srv_report$' -V` checks the refusal line +without a device, with a distinct value in each 2D and 2D-array view field, the raw words of a +cube-array view, and widths, first elements, addresses and destinations above 4 GiB. Checks: diff --git a/tests/startup_memory_srv_report_check.cpp b/tests/startup_memory_srv_report_check.cpp index d239af70b..b05f23772 100644 --- a/tests/startup_memory_srv_report_check.cpp +++ b/tests/startup_memory_srv_report_check.cpp @@ -78,6 +78,67 @@ int main() "view{dim=5 fmt=98 map=0x1688 mostmip=1 mips=5 first=1 count=1 plane=0 clamp=0.5} " "dest=0x1001 dest_in_view_heap=0 address=0x7000 address_readable=1"); + // The same fields with a distinct value each, so that two fields swapped or a first slice + // printed as the count shows up. + auto slices = view(D3D12_SRV_DIMENSION_TEXTURE2DARRAY, DXGI_FORMAT_BC7_UNORM); + slices.Texture2DArray.MostDetailedMip = 4; + slices.Texture2DArray.MipLevels = 2; + slices.Texture2DArray.FirstArraySlice = 0; + slices.Texture2DArray.ArraySize = 1; + slices.Texture2DArray.PlaneSlice = 3; + slices.Texture2DArray.ResourceMinLODClamp = 2.25f; + line(out, "unsupported_description", &bc7, &slices, 0x7000, true, 0x1040, true); + expect("texture array view, distinct fields", out, + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description " + "res{dim=3 fmt=98 size=128x128x2 mips=6 layout=0x105 flags=0x300000 align=65536 samples=1/0} " + "view{dim=5 fmt=98 map=0x1688 mostmip=4 mips=2 first=0 count=1 plane=3 clamp=2.25} " + "dest=0x1040 dest_in_view_heap=1 address=0x7000 address_readable=1"); + + // A 2D view with distinct mip and plane fields and a fractional clamp, at an address and a + // destination above 4 GiB. + D3D12_RESOURCE_DESC r8{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 256, 64, 1, 4, DXGI_FORMAT_R8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + auto plain = view(D3D12_SRV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8_UNORM); + plain.Texture2D.MostDetailedMip = 1; + plain.Texture2D.MipLevels = 2; + plain.Texture2D.PlaneSlice = 3; + plain.Texture2D.ResourceMinLODClamp = 1.5f; + line(out, "unsupported_description", &r8, &plain, 0x200001000ull, true, 0x123456780ull, true); + expect("texture 2D view", out, + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description " + "res{dim=3 fmt=61 size=256x64x1 mips=4 layout=0x0 flags=0x0 align=0 samples=1/0} " + "view{dim=4 fmt=61 map=0x1688 mostmip=1 mips=2 plane=3 clamp=1.5} " + "dest=0x123456780 dest_in_view_heap=1 address=0x200001000 address_readable=1"); + + // Another unnamed dimension: the five fields of a cube-array view as raw words, without the + // acceleration-structure note. + auto cubes = view(D3D12_SRV_DIMENSION_TEXTURECUBEARRAY, DXGI_FORMAT_R8_UNORM); + cubes.TextureCubeArray.MostDetailedMip = 1; + cubes.TextureCubeArray.MipLevels = 2; + cubes.TextureCubeArray.First2DArrayFace = 6; + cubes.TextureCubeArray.NumCubes = 2; + cubes.TextureCubeArray.ResourceMinLODClamp = 0.5f; + line(out, "unsupported_description", &r8, &cubes, 0x2000, true, 0x1000, true); + expect("cube array view", out, + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description " + "res{dim=3 fmt=61 size=256x64x1 mips=4 layout=0x0 flags=0x0 align=0 samples=1/0} " + "view{dim=10 fmt=61 map=0x1688 raw=00000001,00000002,00000006,00000002,3f000000,00000000} " + "dest=0x1000 dest_in_view_heap=1 address=0x2000 address_readable=1"); + + // A buffer wider than 4 GiB and a first element past 2^32 are printed in full. + D3D12_RESOURCE_DESC wide = buffer; + wide.Width = 0x100001000ull; + auto raw = view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_R32_TYPELESS); + raw.Buffer.FirstElement = 0x100000008ull; + raw.Buffer.NumElements = 256; + raw.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + line(out, "unsupported_description", &wide, &raw, 0x2000, true, 0x1000, true); + expect("wide buffer view", out, + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description " + "res{dim=1 fmt=0 size=4294971392x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0} " + "view{dim=1 fmt=39 map=0x1688 first=4294967304 count=256 stride=0 flags=0x1 (buffer views are not supported)} " + "dest=0x1000 dest_in_view_heap=1 address=0x2000 address_readable=1"); + // Memory the guest handed over but the runtime could not read. line(out, "null_destination", nullptr, nullptr, 0, false, 0, false); expect("unreadable arguments", out, @@ -94,6 +155,6 @@ int main() std::printf("FAIL truncated line is not terminated\n"); } if (failures) return 1; - std::printf("slot 70 refusal lines: 4 formats and a truncation exact\n"); + std::printf("slot 70 refusal lines: 8 lines and a truncation exact\n"); return 0; } From 4bbbbdc16bcaf3ab92e11698de864cea203fa270 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Tue, 24 Nov 2026 13:59:33 +0100 Subject: [PATCH 149/775] ci: run the platform-independent Python checks in parallel --- .github/workflows/windows.yml | 98 +++++++++++++++--------------- tests/run_checks_parallel_check.py | 29 +++++++++ tools/run_checks_parallel.py | 46 ++++++++++++++ 3 files changed, 125 insertions(+), 48 deletions(-) create mode 100644 tests/run_checks_parallel_check.py create mode 100644 tools/run_checks_parallel.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index f1c47d01e..2ad756020 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -74,54 +74,56 @@ jobs: run: python -m pip install -r requirements-dev.txt - name: Run Python checks run: | - python -B tests/script_state_check.py - python -B tests/resource_root_check.py - python -B tests/bcpack_check.py - python -B tests/bcpack_symbols_check.py - python -B tests/bcpack_tables_check.py - python -B tests/bc7_blocks_check.py - python -B tests/bc7_tiles_check.py - python -B tests/gfx10_texture_roundtrip_check.py - python -B tests/texture_bc_volume_check.py - python -B tests/form_coverage_check.py - python -B tests/resource_ranges_check.py - python -B tests/ttpf_batch_export_check.py - python -B tests/awc_metadata_check.py - python -B tests/sgd5_effects_check.py - python -B tests/dxcontainer_part_offsets_check.py - python -B tests/layout_chunks_check.py - python -B tests/dependency_paths_check.py - python -B tests/pe_package_preflight_check.py - python -B tests/host_commit_check.py - python -B tests/pe_package_ordinal_plan_check.py - python -B tests/compat_report_check.py - python -B tests/intake/paths_check.py - python -B tests/intake/routing_check.py - python -B tests/intake/import_forms_check.py - python -B tests/shader_probe_check.py - python -B tests/shader_census_check.py - python -B tests/shader_corpus_report_check.py - python -B tests/dxil_retarget_check.py - python -B tests/rdna2_tools_check.py - python -B tests/pso_readiness_check.py - python -B tests/xmem_attribute_scan_check.py - python -B tests/xgameruntime_table_check.py - python -B tests/docs_links_check.py - python -B tests/bidi_controls_check.py - python -B tests/gpu_report_format_check.py - python -B tests/hardware_reports_check.py - python -B tests/rectlist_topology_check.py - python -B tests/startup_sampler_heap_check.py - python -B tests/startup_image_sample_l_check.py - python -B tests/startup_image_3d_check.py - python -B tests/startup_image_load_mip_check.py - python -B tests/startup_image_2d_array_check.py - python -B tests/startup_host_cpu_check.py - python -B tests/startup_translator_check.py - python -B tests/startup_triage_run_check.py - python -B tests/startup_flat_param_check.py - python -B tests/startup_gfx2hlsl_bit_alu_check.py - python -B tests/startup_inline_sampler_check.py + python -B tools/run_checks_parallel.py \ + tests/script_state_check.py \ + tests/resource_root_check.py \ + tests/bcpack_check.py \ + tests/bcpack_symbols_check.py \ + tests/bcpack_tables_check.py \ + tests/bc7_blocks_check.py \ + tests/bc7_tiles_check.py \ + tests/gfx10_texture_roundtrip_check.py \ + tests/texture_bc_volume_check.py \ + tests/form_coverage_check.py \ + tests/resource_ranges_check.py \ + tests/ttpf_batch_export_check.py \ + tests/awc_metadata_check.py \ + tests/sgd5_effects_check.py \ + tests/dxcontainer_part_offsets_check.py \ + tests/layout_chunks_check.py \ + tests/dependency_paths_check.py \ + tests/pe_package_preflight_check.py \ + tests/host_commit_check.py \ + tests/pe_package_ordinal_plan_check.py \ + tests/compat_report_check.py \ + tests/intake/paths_check.py \ + tests/intake/routing_check.py \ + tests/intake/import_forms_check.py \ + tests/shader_probe_check.py \ + tests/shader_census_check.py \ + tests/shader_corpus_report_check.py \ + tests/dxil_retarget_check.py \ + tests/rdna2_tools_check.py \ + tests/pso_readiness_check.py \ + tests/xmem_attribute_scan_check.py \ + tests/xgameruntime_table_check.py \ + tests/docs_links_check.py \ + tests/bidi_controls_check.py \ + tests/gpu_report_format_check.py \ + tests/hardware_reports_check.py \ + tests/rectlist_topology_check.py \ + tests/startup_sampler_heap_check.py \ + tests/startup_image_sample_l_check.py \ + tests/startup_image_3d_check.py \ + tests/startup_image_load_mip_check.py \ + tests/startup_image_2d_array_check.py \ + tests/startup_host_cpu_check.py \ + tests/startup_translator_check.py \ + tests/startup_triage_run_check.py \ + tests/startup_flat_param_check.py \ + tests/startup_gfx2hlsl_bit_alu_check.py \ + tests/startup_inline_sampler_check.py \ + tests/run_checks_parallel_check.py build-and-test: name: Build and test on Windows runs-on: windows-2025 diff --git a/tests/run_checks_parallel_check.py b/tests/run_checks_parallel_check.py new file mode 100644 index 000000000..49606a004 --- /dev/null +++ b/tests/run_checks_parallel_check.py @@ -0,0 +1,29 @@ +"""The parallel check runner reports every script's output and fails when any script fails.""" +import os +import subprocess +import sys +import tempfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RUNNER = os.path.join(ROOT, "tools", "run_checks_parallel.py") + + +def run(*scripts): + return subprocess.run([sys.executable, "-B", RUNNER, "-j", "2", *scripts], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + + +with tempfile.TemporaryDirectory() as tmp: + good = os.path.join(tmp, "good.py") + bad = os.path.join(tmp, "bad.py") + with open(good, "w") as f: + f.write("print('good ran')\n") + with open(bad, "w") as f: + f.write("import sys\nprint('bad ran')\nsys.exit(3)\n") + ok = run(good, good) + assert ok.returncode == 0 and ok.stdout.count("good ran") == 2, ok.stdout + mixed = run(bad, good) + assert mixed.returncode == 1, mixed.stdout + assert "bad ran" in mixed.stdout and "good ran" in mixed.stdout and "FAILED: " + bad in mixed.stdout, mixed.stdout + assert mixed.stdout.index("bad ran") < mixed.stdout.index("good ran"), "output must keep the given order" +print("run_checks_parallel_check: ok") diff --git a/tools/run_checks_parallel.py b/tools/run_checks_parallel.py new file mode 100644 index 000000000..59287884a --- /dev/null +++ b/tools/run_checks_parallel.py @@ -0,0 +1,46 @@ +"""Run independent Python check scripts side by side and fail if any of them fails. + +Usage: + python tools/run_checks_parallel.py [-j N] tests/a_check.py tests/b_check.py ... + +Each script runs as `python -B