diff --git a/CMakeLists.txt b/CMakeLists.txt index a5b4d5e5d5..5395f2496b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1889,6 +1889,16 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") endforeach() +# List slots 14/33/37/39/45: Dispatch and compute root arguments on a console command list. +add_executable(startup_compute_dispatch tests/startup_compute_dispatch.cpp) +target_compile_features(startup_compute_dispatch PRIVATE cxx_std_17) +target_link_libraries(startup_compute_dispatch PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_root_${backend} COMMAND startup_compute_dispatch ${backend}) + set_tests_properties(startup_compute_dispatch_root_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() + add_executable(startup_nv12_draw tests/startup_nv12_draw.cpp tests/desktop_gpu.cpp) target_compile_features(startup_nv12_draw PRIVATE cxx_std_17) target_include_directories(startup_nv12_draw PRIVATE src) @@ -2499,7 +2509,7 @@ endforeach() # Negative control: without slot 43 the first forwarded case is refused, and the fixture must report it. add_test(NAME startup_list_dispatch_native_skip_srv_warp_control COMMAND startup_list_dispatch_native warp skip-srv) set_tests_properties(startup_list_dispatch_native_skip_srv_warp_control PROPERTIES TIMEOUT 60 - PASS_REGULAR_EXPRESSION "bound: expected no Dispatch line, got 1 Dispatch line\\(s\\)[\r\n]+ x2w-render Dispatch\\(2, 3, 1\\) refused: a compute root SRV is not bound") + PASS_REGULAR_EXPRESSION "bound: expected no Dispatch line, got 1 Dispatch line\\(s\\)[\r\n]+ x2w-render Dispatch\\(2, 3, 1\\) refused: a compute root argument is not bound") target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp) target_sources(offscreen_check PRIVATE tests/startup_image_store.cpp) target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp) diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..d1ec72cb17 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -36,7 +36,8 @@ "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", "xmem_page_runs_device_check", "linear_buffer_backing_check", "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", - "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check" + "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check", "startup_compute_dispatch", "startup_root_constant_store", "startup_list_dispatch_check", + "startup_list_dispatch_native", "startup_stream_consumer" ] }, { "name": "release", "configurePreset": "release" }, @@ -50,7 +51,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "name": "^(startup_compute_dispatch_root_warp|startup_compute_dispatch_warp|startup_root_constant_store|startup_list_dispatch[a-z_-]*|bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" } } }, diff --git a/README.md b/README.md index d87c8ed601..d4fead3f6a 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | Startup compute D16 image store | Write [four packed half-floats](docs/experiments.md#startup-compute-d16-image-store) per active thread and check all three mips. | `ctest --preset dev --no-tests=error -R '^startup_compute_image_store_d16'` | | Startup explicit-LOD 2D gather | Dispatch and draw [gfx1013 `image_gather4_l`](docs/experiments.md#explicit-lod-2d-gather) across explicit mips, view offsets, clamped edges, and dynamic per-lane LOD against CPU references. | `ctest --preset dev --no-tests=error -R '^startup_compute_gather_l'` | | Startup compute buffer atomics | Dispatch [gfx1013 32-bit MUBUF raw buffer atomics](docs/experiments.md#startup-compute-raw-buffer-atomics) with thread contention, `glc` old-value returns, `cmpswap` order, and `EXEC` masking. | `ctest --preset dev --no-tests=error -R '^startup_compute_buffer_atomics'` | +| Startup console-list compute bindings | Forward [compute root UAVs and 32-bit root constants](docs/experiments.md#startup-list-dispatch) through the startup runtime and restore them after a shim pass; dispatch and read back the value on WARP and hardware. | `ctest --preset dev --no-tests=error -R '^startup_compute_dispatch_root_' -V` | | 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_'` | diff --git a/docs/experiments.md b/docs/experiments.md index 8506dfdc05..b84b8442c6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -17571,13 +17571,16 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_bit_alu_(controls|warp ## Startup list Dispatch -Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and only root SRV parameters (slot 43), the compute pipeline was built against that same root signature, every root SRV the root declares was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root with other parameters is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV with `a compute root SRV is not bound`. Of the compute root arguments, only root SRVs (slot 43) reach the desktop list: slot 35 records descriptor tables without setting them, and slots 37, 39, 41 and 45 have no handler yet, so a dispatch under any other argument would run with it unset. The first 16 refusals in a process are logged as `x2w-render Dispatch(x, y, z) refused: `. +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and no parameters other than root SRVs (slot 43), root UAVs (slot 45) and 32-bit root constants (slots 37 and 39), the compute pipeline was built against that same root signature, every declared root SRV, root UAV and constant range was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root that declares a parameter of another kind, such as a root CBV, a descriptor table or a static sampler, is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV, root UAV or constant range with `a compute root argument is not bound`. Of the compute root arguments, root SRVs (slot 43), 32-bit root constants (slots 37 and 39) and placed buffer root UAVs (slot 45) reach the desktop list; slot 35 records descriptor tables without setting them, and slot 41 has no handler yet. The first 16 refusals in a process are logged as `x2w-render Dispatch(x, y, z) refused: `. + +`tests/startup_compute_dispatch.cpp` drives slots 86, 25, 33, 37, 39, 45 and 14 of the stand-in on WARP and on a hardware adapter (77 without one) with the debug layer. A subrange at byte 256 is written through a placed buffer root UAV and read back as 59 from the 32 root constants, with sentinels at bytes 0, 128 and 384 untouched. A 33-word write to the 32-word parameter is cut to the words both the store and the desktop list keep, and a same-layout root that wrote its own constants and UAV through the list must be replayed by the restore fixture export before the dispatch reads 59. Calls naming a wrong parameter type or index, an unplaced address, a misaligned address or a rejected placed range must not reach the desktop list, and a Dispatch with an unset root UAV or constant range must be refused. `tests/startup_list_dispatch_check.cpp` checks the decision without a device; its five mutated runs must fail. `tests/startup_list_dispatch_native.cpp` drives slots 86, 25, 33, 43, 148, 14, 9 and 139 of the stand-in on a desktop device, on WARP and on a hardware adapter (77 without one), with the debug layer when it is installed. Each refused case must log exactly one refusal line with the expected reason: a root SRV never set, a rejected or misaligned slot 43 replacement after a valid one, a root changed and changed back without slot 43, a pipeline built against another root, a root with a descriptor table, a root with a static sampler, an unset root SRV with zero groups, more than 65535 groups, a closed list, and a Reset list without new bindings. A forwarded case must log no line. Around each call on an open list the fixture records a pipeline-statistics query on the desktop list: `CSInvocations` must be 4 per group for a forwarded call and 0 for a refused one. The fully bound call is recorded alone and counted first, so a slot 14 that records nothing fails on its count. Each of the three recordings is executed to a fence, and the debug layer must report no error. The shader only declares its root SRV, so this shows that the desktop `Dispatch` is recorded and runs, not what a shader reads through the bound SRV. The `skip_srv` control drops slot 43 from the first forwarded case and must report that case as refused. ```powershell -cmake --build --preset dev --target startup_list_dispatch_check startup_list_dispatch_native +cmake --build --preset dev --target startup_list_dispatch_check startup_list_dispatch_native startup_compute_dispatch ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_root_" -V ``` ## Startup translator: explicit-gradient image_sample_d diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index e32e1246d8..9950533dfe 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -1686,12 +1686,9 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& barrier.UAV.pResource = views[i].resource; list->ResourceBarrier(1, &barrier); } - // The translated root replaced the desktop compute root of the title and its arguments. - if (pass.desktop_compute_root) { - list->SetComputeRootSignature(pass.desktop_compute_root.Get()); - for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) - if (const auto address = pass.desktop_compute_upload_srvs[parameter]) list->SetComputeRootShaderResourceView(parameter, address); - } + // The translated root replaced the desktop compute root of the title and its arguments; replay every one of + // them (root SRVs, root UAVs and 32-bit constants) so a later native Dispatch does not run with them unset. + restore_compute_root(pass, list); ++tr->translated; ReleaseSRWLockExclusive(&draw_lock); static LONG checks; // as translated draws do: the queue's execute drains the rest diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2b012ca84d..0b3bebd1d5 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2674,7 +2674,7 @@ ID3D12Resource* validate_indexed_arguments(Wrapper* self, ID3D12GraphicsCommandL require_state(self, indices, (index_previous & shader_reads) | D3D12_RESOURCE_STATE_INDEX_BUFFER); // The clamp changes the native compute root and invalidates its arguments. - // In render mode slot 43 is the forwarded compute parameter setter. + // In render mode slots 37, 39, 43 and 45 are the forwarded compute parameter setters. restore_compute_root(pass_of(self), list); return scratch.Get(); } @@ -4353,16 +4353,18 @@ void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) log("x2w-render compute descriptor table dropped: parameter %u (%u parameters are kept)", parameter, x2w_startup::ComputeTables::max_parameters); } -// Keeps the words of a root constants call; a call outside the 16 x 8 words kept is logged and cut or dropped. -static void store_root_constants(x2w_root_constants::Store& store, const char* kind, UINT parameter, UINT count, - const std::uint32_t* data, UINT offset) +// Keeps the words of a root constants call; a call outside the kept words is logged and cut or dropped. Returns the +// number of words from `offset` that the store kept, so the caller forwards exactly the words the store recorded. +static UINT store_root_constants(x2w_root_constants::Store& store, const char* kind, UINT parameter, UINT count, + const std::uint32_t* data, UINT offset, UINT capacity = x2w_root_constants::words_per_parameter) { - if (!count || !x2w_local::readable(data, std::size_t{count} * 4)) return; - const auto result = store.set(parameter, count, data, offset); + if (!count || !x2w_local::readable(data, std::size_t{count} * 4)) return 0; + const auto result = store.set(parameter, count, data, offset, capacity); static LONG refused; if (result != x2w_root_constants::Result::stored && first_calls(refused, 4)) - log("x2w-render %s root constants %s: parameter %u, offset %u, count %u (16 parameters of 8 words are kept)", kind, - result == x2w_root_constants::Result::dropped ? "dropped" : "truncated", parameter, offset, count); + log("x2w-render %s root constants %s: parameter %u, offset %u, count %u (%u words are kept)", kind, + result == x2w_root_constants::Result::dropped ? "dropped" : "truncated", parameter, offset, count, capacity); + return result == x2w_root_constants::Result::dropped ? 0 : (std::min)(count, capacity - offset); } // List slot 40 (desktop 36 + 4), SetGraphicsRoot32BitConstants(parameter, count, data, offset). void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) @@ -4382,12 +4384,33 @@ void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, co // List slot 37 (desktop 33 + 4), SetComputeRoot32BitConstant(parameter, value, offset). void __stdcall list_compute_constant(Wrapper* self, UINT parameter, UINT value, UINT offset) { - store_root_constants(pass_of(self).compute_constants, "compute", parameter, 1, &value, offset); + Pass& pass = pass_of(self); + UINT capacity = x2w_root_constants::words_per_parameter; + const auto* params = pass.compute_params; + const bool valid_param = params && parameter < params->size() && + (*params)[parameter].type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + if (valid_param) { + capacity = (std::min)(x2w_root_constants::max_words_per_parameter, (*params)[parameter].constants_count); + } + const UINT kept = store_root_constants(pass.compute_constants, "compute", parameter, 1, &value, offset, capacity); + if (auto* list = recording(self); list && pass.desktop_compute_root && valid_param && kept) + list->SetComputeRoot32BitConstant(parameter, value, offset); } // List slot 39 (desktop 35 + 4), SetComputeRoot32BitConstants(parameter, count, data, offset). void __stdcall list_compute_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) { - store_root_constants(pass_of(self).compute_constants, "compute", parameter, count, data, offset); + Pass& pass = pass_of(self); + UINT capacity = x2w_root_constants::words_per_parameter; + const auto* params = pass.compute_params; + const bool valid_param = params && parameter < params->size() && + (*params)[parameter].type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + if (valid_param) { + capacity = (std::min)(x2w_root_constants::max_words_per_parameter, (*params)[parameter].constants_count); + } + // Forward exactly the words the store kept, so a dispatch never runs with words one side has and the other does not. + const UINT kept = store_root_constants(pass.compute_constants, "compute", parameter, count, data, offset, capacity); + if (auto* list = recording(self); list && pass.desktop_compute_root && valid_param && kept) + list->SetComputeRoot32BitConstants(parameter, kept, data, offset); } // List slot 47 (desktop 43 + 4), IASetIndexBuffer(view). void __stdcall list_index_buffer(Wrapper* self, const D3D12_INDEX_BUFFER_VIEW* view) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0a3ddf5832..d63b4e9485 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -275,7 +275,7 @@ struct alignas(16) WrapperOwn { ID3D12RootSignature* pipeline_root; // PipelineState: desktop root signature its compute stream declared u64 compute_request_key; // PipelineState: key of the slot 67 request it published, or 0 const void* compute_request_root; // PipelineState: root signature wrapper named by that slot 67 description - bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) + bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a forwarded root argument (SRV, UAV, constants) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) Wrapper* list_device; // CommandList: wrapper that created this list. @@ -3002,7 +3002,10 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v w->own().root_srv_only = !heap_flags && !desc->Desc_1_1.NumStaticSamplers && desc->Desc_1_1.NumParameters; for (UINT i = 0; i < desc->Desc_1_1.NumParameters; ++i) { const auto& parameter = desc->Desc_1_1.pParameters[i]; - if (parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV) w->own().root_srv_only = false; + if (parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV && + parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_UAV && + parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) + w->own().root_srv_only = false; RootParameter info{parameter.ParameterType, 0, 0}; if (parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV) { @@ -3489,11 +3492,11 @@ struct Pass { std::array desktop_compute_upload_srvs{}; ID3D12RootSignature* compute_pipeline_root = nullptr; // root the bound compute pipeline was built against UINT compute_srv_bound = 0; // root SRV parameters that reached the desktop list since slot 33 - // Desktop root UAVs a fixture bound through x2w_d3d12_fixture_compute_root_uav, set again after a shim compute pass. + // Desktop root UAVs bound through slot 45 or x2w_d3d12_fixture_compute_root_uav, set again after a shim compute pass. std::array desktop_compute_root_uavs{}; const std::vector* compute_params = nullptr; std::unique_ptr compute_trace; - bool compute_root_has_arguments = false; // that root declares parameters other than root SRVs, or static samplers + bool compute_root_has_arguments = false; // that root declares parameters other than root SRVs, root UAVs and 32-bit constants, or static samplers IndirectGraphicsPipeline indirect_graphics; ID3D12RootSignature* graphics_root = nullptr; bool targets_bound = false; @@ -3990,9 +3993,9 @@ UINT __stdcall list_resource_barriers(Wrapper* self, UINT count, const D3D12_RES return 0; // no console barrier actions to perform on the caller's side } -// Compute root views on the desktop list. Root SRVs come from slot 43; root UAVs only from the fixture hook -// x2w_d3d12_fixture_compute_root_uav (slot 45 is not forwarded). Both are recorded here so restore_compute_root can set -// them again after a shim compute pass has replaced the desktop compute root. +// Compute root views on the desktop list. Root SRVs come from slot 43; root UAVs from slot 45 or the fixture hook +// x2w_d3d12_fixture_compute_root_uav. Both are recorded here so restore_compute_root can set them again after a shim +// compute pass has replaced the desktop compute root. void bind_compute_root_view(Pass& pass, ID3D12GraphicsCommandList* list, UINT parameter, D3D12_ROOT_PARAMETER_TYPE type, D3D12_GPU_VIRTUAL_ADDRESS address) { @@ -4022,6 +4025,27 @@ void restore_compute_root(const Pass& pass, ID3D12GraphicsCommandList* list) if (const auto address = pass.desktop_compute_root_uavs[parameter]) list->SetComputeRootUnorderedAccessView(parameter, address); } + if (const auto* params = pass.compute_params) { + for (UINT parameter = 0; parameter < params->size() && parameter < 16; ++parameter) { + const auto& p = (*params)[parameter]; + if (p.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { + const UINT declared = (std::min)(p.constants_count, x2w_root_constants::max_words_per_parameter); + UINT offset = 0; + while (offset < declared) { + if (!(pass.compute_constants.bound[parameter] & (1u << offset))) { + ++offset; + continue; + } + UINT count = 0; + while (offset + count < declared && (pass.compute_constants.bound[parameter] & (1u << (offset + count)))) { + ++count; + } + list->SetComputeRoot32BitConstants(parameter, count, &pass.compute_constants.words[parameter][offset], offset); + offset += count; + } + } + } + } } void __stdcall list_compute_root(Wrapper* self, void* root) @@ -4030,11 +4054,13 @@ void __stdcall list_compute_root(Wrapper* self, void* root) if (!list) return; Wrapper* w = as_wrapper(root); Pass& pass = pass_of(self); - // A different root signature invalidates the title's cached compute root arguments. + // A different root signature invalidates the title's cached compute root arguments. That includes the root UAVs + // when the desktop root object stays the same (root, null, same root): Dispatch must not pass on a stale address. if (pass.compute_root_wrapper != w) { pass.compute_constants.clear(); pass.compute_root_srvs.fill(0); pass.compute_root_srv_set = 0; + pass.desktop_compute_root_uavs.fill(0); } pass.compute_root_wrapper = w; const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); @@ -4042,15 +4068,12 @@ void __stdcall list_compute_root(Wrapper* self, void* root) pass.compute_tables.set_signature(w ? root_info(w) : nullptr); // a different signature leaves no table bound pass.compute_params = real ? root_info(w) : nullptr; pass.compute_srv_bound = 0; - // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. + // Root SRV, root UAV and 32-bit constant parameters are forwarded by their own slots; anything else the root declares is not. pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (compute_binding_trace_enabled() && (!pass.compute_trace || pass.compute_trace->root != w)) { pass.compute_trace = std::make_unique(); pass.compute_trace->root = w; } - pass.compute_srv_bound = 0; - // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. - pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (pass.compute_root) { if (pass.desktop_compute_root.Get() != pass.compute_root) { pass.desktop_compute_upload_srvs.fill(0); @@ -4062,10 +4085,9 @@ void __stdcall list_compute_root(Wrapper* self, void* root) } // Fixture binding of a desktop root UAV (a desktop GPU address) on a guest list's recording, under the compute root -// set through slot 33. Not a guest slot: titles have no compute root UAV on the desktop list (slot 45 is not -// forwarded). It records the view through bind_compute_root_view, as slot 43 does for root SRVs, so -// restore_compute_root sets it again after a shim compute pass; a binding made on the desktop list directly would be -// lost there. +// set through slot 33. It records the view through bind_compute_root_view, as slot 43 does for root SRVs and slot 45 +// for placed buffer UAVs, so restore_compute_root sets it again after a shim compute pass; a binding made on the +// desktop list directly would be lost there. extern "C" __declspec(dllexport) BOOL x2w_d3d12_fixture_compute_root_uav(void* guest_list, UINT parameter, UINT64 address) { Wrapper* self = as_wrapper(guest_list); @@ -4081,6 +4103,19 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_fixture_compute_root_uav(void* g return TRUE; } +// Fixture call to restore the compute root signature and its recorded arguments (root SRVs, root UAVs, +// and 32-bit root constants) on a guest list's desktop recording after a shim compute pass. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_fixture_restore_compute_root(void* guest_list) +{ + Wrapper* self = as_wrapper(guest_list); + if (!self || self->own().kind != list_kind) return FALSE; + auto* list = recording(self); + const auto& pass = pass_of(self); + if (!list || !pass.desktop_compute_root) return FALSE; + restore_compute_root(pass, list); + return TRUE; +} + // Query slots 28 to 30, confirmed by the GXDK 261000 ID3D12GraphicsCommandList8 function table // (command_list_slot_names.h): they are bound only with X2W_D3D12_QUERY_SLOTS=1 because the behavior is // diagnostic. The heap reaches device slot 39 with the desktop desc. Only occlusion queries are @@ -4850,7 +4885,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (!scratch || !x2w_startup::rect_indirect_arguments().convert(list, resource, offset, scratch)) return refuse("rectangle-list argument conversion is unavailable", indirect_other, indirect_other_refusal_code::rect_conversion_unavailable); - if (pass.desktop_compute_root) list->SetComputeRootSignature(pass.desktop_compute_root.Get()); + restore_compute_root(pass, list); // the conversion set its own root; replay the title's arguments too list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); draw_arguments = scratch; draw_offset = 0; @@ -4921,7 +4956,8 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (split) { // The rewrite reads the title's records and count word by copies only, then replaces the compute root and // pipeline. The compute state the title can set on the desktop list is the pipeline (slot 25), the root - // (slot 33) and root SRVs (slot 43); the other compute root setters are not forwarded. The pipeline is set + // (slot 33), root SRVs (slot 43), 32-bit constants (slots 37/39) and root UAVs (slot 45); the other compute + // root setters are not forwarded. The pipeline is set // again here and the root with its views by restore_compute_root, the same code as after the indexed-draw // validation pass, before the single-command calls. auto* desktop = device_of(self->own().list_device); @@ -5451,6 +5487,53 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add } } +// List slot 45 (desktop 41 + 4), SetComputeRootUnorderedAccessView(parameter, title GPU address). +void __stdcall list_compute_root_uav(Wrapper* self, UINT parameter, u64 address) +{ + if (parameter >= 16) return; + Pass& pass = pass_of(self); + if (compute_binding_trace_enabled()) { + trace_compute_binding(self, 45, parameter, address, 0, 0); + } + auto* list = recording(self); + const auto* params = pass.compute_params; + if (!list || !pass.desktop_compute_root || !params || parameter >= params->size() || + parameter >= pass.desktop_compute_root_uavs.size() || + (*params)[parameter].type != D3D12_ROOT_PARAMETER_TYPE_UAV) { + if (parameter < pass.desktop_compute_root_uavs.size()) pass.desktop_compute_root_uavs[parameter] = 0; + return; + } + + // A root UAV is written by the shader, so it must be an aliased placed buffer with unordered access: upload + // pages are read-only for shaders, and a copied placement would not show the write to the title. + D3D12_GPU_VIRTUAL_ADDRESS desktop = 0; + const auto placed = placed_buffer_range(self->own().list_device, address, 1); + if (!placed.reject && placed.owner && placed.alias && + (placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const auto base = reinterpret_cast(placed.owner->own().title_memory); + const auto gpu_base = placed.alias->GetGPUVirtualAddress(); + const auto offset = address - base; + if (gpu_base && offset <= ~u64{} - gpu_base) desktop = gpu_base + offset; + } + if (desktop && !(desktop % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)) { + bind_compute_root_view(pass, list, parameter, D3D12_ROOT_PARAMETER_TYPE_UAV, desktop); + static LONG logged; + if (first_calls(logged, 4)) + log("x2w-render compute root UAV %u: title 0x%llx -> desktop 0x%llx", parameter, address, desktop); + } else { + pass.desktop_compute_root_uavs[parameter] = 0; + static LONG misaligned_logged, unplaced_logged; + if (desktop) { + if (first_calls(misaligned_logged, 4)) + log("x2w-render compute root UAV %u: title 0x%llx maps to desktop 0x%llx, which is not %u-byte aligned", + parameter, address, desktop, static_cast(D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)); + } else if (first_calls(unplaced_logged, 4)) { + log("x2w-render compute root UAV %u: title 0x%llx is not an aliased placed buffer range with unordered access", + parameter, address); + } + } +} + // List slot 44 (desktop 40 + 4), SetGraphicsRootShaderResourceView(parameter, title GPU address). void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) { @@ -5543,8 +5626,23 @@ void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) request.compute_root = pass.compute_root != nullptr; request.compute_root_has_arguments = pass.compute_root_has_arguments; request.root_matches_pipeline = pass.compute_pipeline_root && pass.compute_pipeline_root == pass.compute_root; - const UINT count = pass.compute_params ? static_cast(pass.compute_params->size()) : 0; - request.root_arguments_bound = count <= 32 && (pass.compute_srv_bound & (count >= 32 ? ~0u : (1u << count) - 1)) == (count >= 32 ? ~0u : (1u << count) - 1); + bool all_bound = true; + if (pass.compute_params) { + for (UINT i = 0; i < pass.compute_params->size(); ++i) { + const auto& p = (*pass.compute_params)[i]; + if (p.type == D3D12_ROOT_PARAMETER_TYPE_SRV) { + if (i >= 32 || !(pass.compute_srv_bound & (1u << i))) { all_bound = false; break; } + } else if (p.type == D3D12_ROOT_PARAMETER_TYPE_UAV) { + if (i >= pass.desktop_compute_root_uavs.size() || !pass.desktop_compute_root_uavs[i]) { all_bound = false; break; } + } else if (p.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { + const UINT cap = (std::min)(32u, p.constants_count); + if (!pass.compute_constants.is_bound(i, 0, p.constants_count, cap)) { all_bound = false; break; } + } else { + all_bound = false; break; + } + } + } + request.root_arguments_bound = all_bound; request.x = x, request.y = y, request.z = z; const x2w_startup::DispatchDecision decision = x2w_startup::decide_dispatch(request); if (decision != x2w_startup::DispatchDecision::forward) { @@ -9233,6 +9331,8 @@ void build_tables() list_typed[43] = reinterpret_cast(&list_compute_upload_srv); list_typed[44] = reinterpret_cast(&list_root_srv); list_typed[42] = reinterpret_cast(&list_root_cbv); + list_typed[45] = reinterpret_cast(&list_compute_root_uav); + tables[list_kind][45] = reinterpret_cast(&list_compute_root_uav); list_typed[50] = reinterpret_cast(&list_targets); list_typed[13] = reinterpret_cast(&list_draw_indexed); list_typed[35] = reinterpret_cast(&list_compute_table); diff --git a/src/startup_stubs/list_dispatch.h b/src/startup_stubs/list_dispatch.h index 102446d710..649f6395b5 100644 --- a/src/startup_stubs/list_dispatch.h +++ b/src/startup_stubs/list_dispatch.h @@ -2,8 +2,11 @@ // Command-list slot 14, Dispatch(x, y, z). A dispatch is forwarded to the desktop list only when the list is open, // can run compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares -// no parameters other than root SRVs (of the compute root-argument slots, only slot 43 (root SRV) is forwarded; 35, 37, 39, 41 and 45 are not forwarded yet, so a root that needs -// arguments would run with them unset), and every group count is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. +// no parameters other than the forwarded kinds (root SRVs through slot 43, root UAVs through slot 45, and 32-bit +// constants through slots 37 and 39; descriptor tables through slot 35, root CBVs and static samplers are not +// forwarded, so a root that needs one would run with it unset), the compute pipeline was built against that same root +// signature, every declared root argument is bound, and every group count is within the D3D12 limit of 65535 per +// dimension. Zero groups on any axis is valid and runs nothing. #include @@ -18,7 +21,7 @@ struct ListDispatch { bool compute_root = false; // the bound compute root signature is a desktop root signature bool compute_root_has_arguments = false; // that root declares parameters or static samplers bool root_matches_pipeline = true; // the compute pipeline was built against the bound compute root - bool root_arguments_bound = true; // every root SRV the root declares reached the desktop list (a rejected set clears it) + bool root_arguments_bound = true; // every root SRV, root UAV and 32-bit constant range the root declares reached the desktop list (a rejected set clears it) UINT x = 0, y = 0, z = 0; }; @@ -35,7 +38,7 @@ inline const char* dispatch_reason(DispatchDecision decision) case DispatchDecision::no_compute_state: return "requires a desktop compute pipeline and root"; case DispatchDecision::unforwarded_root_arguments: return "compute root arguments are not forwarded"; case DispatchDecision::root_pipeline_mismatch: return "compute pipeline was built against another root signature"; - case DispatchDecision::unbound_root_argument: return "a compute root SRV is not bound"; + case DispatchDecision::unbound_root_argument: return "a compute root argument is not bound"; case DispatchDecision::group_count_over_limit: return "group count is over 65535"; } return "unknown"; diff --git a/src/startup_stubs/root_constant_store.h b/src/startup_stubs/root_constant_store.h index 45b9914008..7899b46ffd 100644 --- a/src/startup_stubs/root_constant_store.h +++ b/src/startup_stubs/root_constant_store.h @@ -1,8 +1,9 @@ // Experimental (docs/startup-runtime.md, #870): the 32-bit compute root arguments a recorded command list keeps // (list slots 37 and 39; the graphics slot 40 keeps its own words). Plain standard C++ with no Windows types, so it can be tested on its own. // -// A list keeps 16 root parameters of 8 words each. A write that starts past those limits is dropped and one -// that runs past them is cut off at the end of the parameter, so the caller can log either case. +// A list keeps up to 16 root parameters of up to 32 words each (native slot 86 roots declare up to 32 words; +// translated compute defaults to 8 words). A write that starts past the parameter's capacity is dropped and one +// that runs past it is cut off at the end of the parameter, so the caller can log either case. #pragma once #include @@ -12,14 +13,15 @@ namespace x2w_root_constants { inline constexpr unsigned parameter_count = 16; inline constexpr unsigned words_per_parameter = 8; +inline constexpr unsigned max_words_per_parameter = 32; enum class Result { stored, truncated, dropped }; struct Store { - std::uint32_t words[parameter_count][words_per_parameter] = {}; + std::uint32_t words[parameter_count][max_words_per_parameter] = {}; // One bit per word that a write stored, like the graphics path's `constant_words_bound`, so a later // dispatch can tell "set to 0" from "never set". - std::uint8_t bound[parameter_count] = {}; + std::uint32_t bound[parameter_count] = {}; void clear() noexcept { @@ -29,33 +31,40 @@ struct Store { } // True when every word in [offset, offset + count) of `parameter` was written since the last clear. - bool is_bound(unsigned parameter, unsigned offset, unsigned count) const noexcept + bool is_bound(unsigned parameter, unsigned offset, unsigned count, unsigned capacity = words_per_parameter) const noexcept { - if (!count || parameter >= parameter_count || offset >= words_per_parameter || count > words_per_parameter - offset) + if (!count || parameter >= parameter_count || offset >= capacity || count > capacity - offset || capacity > max_words_per_parameter) return false; - const unsigned mask = ((1u << count) - 1) << offset; + const std::uint32_t mask = count >= 32 ? ~0u : (((1u << count) - 1) << offset); return (bound[parameter] & mask) == mask; } // SetXxxRoot32BitConstants(parameter, count, data, offset). `data` must hold `count` words. - Result set(unsigned parameter, unsigned count, const std::uint32_t* data, unsigned offset) noexcept + Result set(unsigned parameter, unsigned count, const std::uint32_t* data, unsigned offset, + unsigned capacity = words_per_parameter) noexcept { - if (!count || !data || parameter >= parameter_count || offset >= words_per_parameter) return Result::dropped; - const bool cut = count > words_per_parameter - offset; - const unsigned n = cut ? words_per_parameter - offset : count; + if (!count || !data || parameter >= parameter_count || offset >= capacity || capacity > max_words_per_parameter) + return Result::dropped; + const bool cut = count > capacity - offset; + const unsigned n = cut ? capacity - offset : count; for (unsigned i = 0; i < n; ++i) words[parameter][offset + i] = data[i]; - bound[parameter] |= static_cast(((1u << n) - 1) << offset); + const std::uint32_t mask = n >= 32 ? ~0u : (((1u << n) - 1) << offset); + bound[parameter] |= mask; return cut ? Result::truncated : Result::stored; } // SetXxxRoot32BitConstant(parameter, value, offset). - Result set_one(unsigned parameter, std::uint32_t value, unsigned offset) noexcept { return set(parameter, 1, &value, offset); } + Result set_one(unsigned parameter, std::uint32_t value, unsigned offset, + unsigned capacity = words_per_parameter) noexcept + { + return set(parameter, 1, &value, offset, capacity); + } // The word a shader reads; 0 outside the kept range. std::uint32_t word(int parameter, int offset) const noexcept { return parameter >= 0 && parameter < static_cast(parameter_count) && offset >= 0 && - offset < static_cast(words_per_parameter) + offset < static_cast(max_words_per_parameter) ? words[parameter][offset] : 0; } diff --git a/tests/standin_exports_check.py b/tests/standin_exports_check.py index 53031b94a0..cc3dd7505b 100644 --- a/tests/standin_exports_check.py +++ b/tests/standin_exports_check.py @@ -107,7 +107,7 @@ def test_real_catalogs(): expected = set(modules[:8]) | {"xgameruntime.dll"} check(set(catalogs) == expected, f"load_catalogs keys {sorted(catalogs)} != {sorted(expected)}") - counts = {"xmem": 54, "d3d12_xs": 79, "acphal": 10, "chad": 5, + counts = {"xmem": 54, "d3d12_xs": 80, "acphal": 10, "chad": 5, "xapu": 6, "xcrdapi": 3, "xg_xs": 2, "gameinput": 2} for stem, path in DEFAULT_DEFS.items(): catalog = catalogs[stem + ".dll"] @@ -146,7 +146,7 @@ def test_real_catalogs(): == Counter({"trap": 9, "implemented": 1}), "acphal status counts differ") check(Counter(e.status for e in catalogs["d3d12_xs.dll"].entries.values()) - == Counter({"implemented": 35, "unmeasured": 44}), + == Counter({"implemented": 35, "unmeasured": 45}), "d3d12_xs status counts differ") check(Counter(e.status for e in catalogs["xgameruntime.dll"].entries.values()) == Counter({"implemented": 38}), @@ -221,7 +221,7 @@ def test_real_catalogs(): check(d3d12.lookup("x2w_d3d12_compute_census").status == "unmeasured", "d3d12_xs direct export is unmeasured") check(d3d12.lookup("x2w_d3d12_compute_census").source - == "src/startup_stubs/d3d12_compute_dispatch.inl:1744", + == "src/startup_stubs/d3d12_compute_dispatch.inl:1741", "d3d12_xs direct export source is the included file") check(d3d12.lookup("NoSuchExport").status == "absent", "d3d12_xs absent name") @@ -270,7 +270,7 @@ def test_export_coverage(): "src/xmem_shim.def:15", None), ("d3d12_xs.dll", "x2w_d3d12_compute_census", "unmeasured", "d3d12_xs.dll", "shim", - "src/startup_stubs/d3d12_compute_dispatch.inl:1744", None), + "src/startup_stubs/d3d12_compute_dispatch.inl:1741", None), ("d3d12_xs.dll", "IID_ID3D12Device", "implemented", "d3d12_xs.dll", "shim", "src/d3d12_xs_shim.def:13", "src/d3d12_xs_iids.cpp:1"), ("xgameruntime.dll", "XUserAddAsync", "implemented", diff --git a/tests/startup_compute_dispatch.cpp b/tests/startup_compute_dispatch.cpp new file mode 100644 index 0000000000..8b1dfa2fe7 --- /dev/null +++ b/tests/startup_compute_dispatch.cpp @@ -0,0 +1,578 @@ +// Direct compute dispatch and root argument bindings on a console command list. +// +// startup_compute_dispatch (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 X2W_D3D12_DEBUG=1) +// +// Verifies: +// - CommandList slot 33: SetComputeRootSignature +// - CommandList slot 25: SetPipelineState (compute) +// - CommandList slot 37: SetComputeRoot32BitConstant (forward of word 0 and word 31 before a restore replay) +// - CommandList slot 39: SetComputeRoot32BitConstants (32 constants, range checking, a write past the declared words is cut to the kept words) +// - CommandList slot 45: SetComputeRootUnorderedAccessView (placed subrange offset handling, reject check, and +// refusal of upload memory and of placed buffers that are not aliased or lack unordered access) +// - CommandList slot 14: Dispatch(x, y, z) +// - Correct execution on GPU, subrange write to offset 256 and sentinel preserved at offset 0. +// - Restoring the compute root after a same-layout root wrote its own constants and UAV through it. +// - A slot 37 write at word 31 after the full slot 39 write reaches the desktop root before the restore +// replay, checked at offset 192 (scale 5, bias 7, extra 4 -> 61). Without the forward it reads 39; with +// the translated 8-word capacity it reads 59. +// - A Dispatch after only part of the root constants was written is refused and leaves sentinel 0x66666666 +// at offset 64 untouched. +// - After slot 33 with null and the same root again, a Dispatch with the constants rebound but no slot 45 call +// is refused and leaves sentinel 0x44444444 at offset 384 untouched. +// - Negative controls: Dispatch without a compute pipeline, with 0 groups and with 1 group. +// - Zero debug layer errors and healthy desktop device. +// +// Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +using u64 = std::uint64_t; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_fixture_restore_compute_root(void*); + +namespace { +template +Method slot(IUnknown* object, unsigned index) +{ + return reinterpret_cast((*reinterpret_cast(object))[index]); +} + +template +ComPtr native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object) +{ + constexpr GUID key{0x10a62244, 0x1615, 0x4953, {0xa2, 0x52, 0xbe, 0x42, 0x35, 0x27, 0xa0, 0x61}}; + guest->SetPrivateDataInterface(key, object); + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); + guest->SetPrivateDataInterface(key, nullptr); + if (FAILED(read) || !stored) return nullptr; + ComPtr result; + stored.As(&result); + return result; +} + +constexpr char shader_source[] = R"( +RWByteAddressBuffer data : register(u0); +cbuffer RootConstants : register(b0) { + uint scale; + uint bias; + uint2 pad2; + uint4 pad4[6]; + uint3 pad3; + uint extra; +}; + +[numthreads(1, 1, 1)] +void cs_main(uint3 group : SV_GroupID) { + uint val = scale * (10 + group.x) + bias + extra; + data.Store(0, val); +} +)"; + +ComPtr compile_cs() +{ + ComPtr code, errors; + const HRESULT hr = D3DCompile(shader_source, sizeof(shader_source) - 1, nullptr, nullptr, nullptr, + "cs_main", "cs_5_0", 0, 0, &code, &errors); + if (FAILED(hr) && errors) std::fprintf(stderr, "%s\n", static_cast(errors->GetBufferPointer())); + return SUCCEEDED(hr) ? code : nullptr; +} + +std::atomic debug_error_count{0}; +void WINAPI on_message(D3D12_MESSAGE_CATEGORY, D3D12_MESSAGE_SEVERITY severity, D3D12_MESSAGE_ID, LPCSTR text, void*) +{ + if (severity > D3D12_MESSAGE_SEVERITY_ERROR) return; + if (++debug_error_count <= 12) std::printf("debug layer: %.300s\n", text); +} + +struct Probe { + ComPtr desktop; + DWORD cookie = 0; + ComPtr queue1; + bool watch() + { + return SUCCEEDED(desktop.As(&queue1)) && + SUCCEEDED(queue1->RegisterMessageCallback(on_message, D3D12_MESSAGE_CALLBACK_FLAG_NONE, nullptr, &cookie)); + } +}; + +void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* res, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = res; + barrier.Transition.StateBefore = from; + barrier.Transition.StateAfter = to; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + list->ResourceBarrier(1, &barrier); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) return 2; + const bool warp = std::strcmp(argv[1], "warp") == 0; + + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + + ComPtr adapter; + if (warp) { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return 3; + } else { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } + if (!adapter) return warp ? 1 : 77; + + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::wprintf(L"adapter=%s\n", adapter_desc.Description); + + Probe probe; + std::array parameters{}; + ComPtr guest; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), reinterpret_cast(guest.GetAddressOf())))) + return 4; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&probe.desktop)))) return 4; + + if (!probe.watch()) std::printf("no debug layer message callback: validation not counted\n"); + + // 1. Create compute root signature: + // Param 0: UAV (u0, space 0) + // Param 1: 32-bit constants (32 DWORDs at b0, space 0) + D3D12_ROOT_PARAMETER root_params[2]{}; + root_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + root_params[0].Descriptor.ShaderRegister = 0; + root_params[0].Descriptor.RegisterSpace = 0; + root_params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + + root_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + root_params[1].Constants = {0, 0, 32}; + root_params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, root_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr serialized_root; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized_root, nullptr))) + return 5; + + ComPtr guest_root; + using CreateRootFn = HRESULT (WINAPI*)(IUnknown*, UINT, const void*, SIZE_T, REFIID, void**); + if (FAILED(slot(guest.Get(), 16)(guest.Get(), 0, serialized_root->GetBufferPointer(), + serialized_root->GetBufferSize(), __uuidof(ID3D12RootSignature), + reinterpret_cast(guest_root.GetAddressOf())))) + return 7; + + // 2. Create compute pipeline state + const auto cs_bytecode = compile_cs(); + if (!cs_bytecode) return 8; + + struct StreamDesc { + alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE root_type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE; + ID3D12RootSignature* root = nullptr; + alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE cs_type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS; + D3D12_SHADER_BYTECODE code{}; + } stream{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, guest_root.Get(), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, {cs_bytecode->GetBufferPointer(), cs_bytecode->GetBufferSize()}}; + const D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(stream), &stream}; + + using CreateStreamFn = HRESULT (WINAPI*)(IUnknown*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + ComPtr guest_pipeline; + if (FAILED(slot(guest.Get(), 86)(guest.Get(), &stream_desc, __uuidof(ID3D12PipelineState), + reinterpret_cast(guest_pipeline.GetAddressOf())))) + return 9; + + // 3. Create placed UAV buffer (512 bytes) via device slot 133 + void* guest_mem = VirtualAlloc(nullptr, 512, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!guest_mem) return 10; + + const D3D12_RESOURCE_DESC placed_desc{ + D3D12_RESOURCE_DIMENSION_BUFFER, 0, 512, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + }; + using PlaceFn = HRESULT (WINAPI*)(void*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, const GUID*, void**); + ComPtr placed_wrapper; + if (FAILED(slot(guest.Get(), 133)(guest.Get(), guest_mem, &placed_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, &__uuidof(ID3D12Resource), + reinterpret_cast(placed_wrapper.GetAddressOf())))) + return 10; + + const auto placed_res = native_object(probe.desktop.Get(), guest.Get(), placed_wrapper.Get()); + if (!placed_res) return 10; + + // Create staging upload buffer and readback buffer (512 bytes each) + D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC buffer_desc{ + D3D12_RESOURCE_DIMENSION_BUFFER, 0, 512, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE + }; + + ComPtr init_buffer, readback_buffer, copied_readback; + if (FAILED(probe.desktop->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&init_buffer))) || + FAILED(probe.desktop->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback_buffer))) || + FAILED(probe.desktop->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&copied_readback)))) + return 10; + + // Pre-populate buffer with sentinels at offsets 0, 64, 128, 192, 384, 448 and initial pattern at offset 256 + void* init_map = nullptr; + if (FAILED(init_buffer->Map(0, nullptr, &init_map))) return 10; + std::memset(init_map, 0, 512); + *reinterpret_cast(init_map) = 0x11111111u; // Sentinel before subrange + *reinterpret_cast(reinterpret_cast(init_map) + 64) = 0x66666666u; // Sentinel pinning partial-constants mutant + *reinterpret_cast(reinterpret_cast(init_map) + 128) = 0x33333333u; // Sentinel pinning unset constants mutant + *reinterpret_cast(reinterpret_cast(init_map) + 192) = 0x77777777u; // Target pinning the slot 37 forward and capacity mutants + *reinterpret_cast(reinterpret_cast(init_map) + 256) = 0x22222222u; // Initial value at subrange + *reinterpret_cast(reinterpret_cast(init_map) + 384) = 0x44444444u; // Sentinel pinning unset UAV / alignment mutant + *reinterpret_cast(reinterpret_cast(init_map) + 448) = 0x55555555u; // Target for the cut-write dispatch + init_buffer->Unmap(0, nullptr); + + // 4. Create CommandQueue, CommandAllocator, CommandList, Fence + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr queue; + ComPtr fence; + if (FAILED(probe.desktop->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue))) || + FAILED(probe.desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) + return 11; + + ComPtr allocator; + if (FAILED(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))) + return 11; + + using CreateListFn = HRESULT (WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + ComPtr guest_list; + if (FAILED(slot(guest.Get(), 73)(guest.Get(), list_desc, allocator.Get(), nullptr, + __uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(guest_list.GetAddressOf())))) + return 11; + + using ResetFn = HRESULT (WINAPI*)(IUnknown*, IUnknown*, void*); + if (FAILED(slot(guest_list.Get(), 139)(guest_list.Get(), allocator.Get(), nullptr))) + return 12; + + const auto desktop_list = native_object(probe.desktop.Get(), guest.Get(), guest_list.Get()); + if (!desktop_list) return 13; + + // Initialize placed buffer with sentinel and subrange pattern, then transition to UNORDERED_ACCESS + transition(desktop_list.Get(), placed_res.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + desktop_list->CopyBufferRegion(placed_res.Get(), 0, init_buffer.Get(), 0, 512); + transition(desktop_list.Get(), placed_res.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + // 5. Negative controls: + // Negative control 1: Dispatch with 0 groups and no compute pipeline -> refused + using DispatchFn = void (WINAPI*)(IUnknown*, UINT, UINT, UINT); + slot(guest_list.Get(), 14)(guest_list.Get(), 0, 1, 1); + + // Negative control 2: Dispatch without a compute pipeline -> refused + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // 6. Bind compute pipeline and root signature + // Slot 25: SetPipelineState + using PipelineFn = void (WINAPI*)(IUnknown*, IUnknown*); + slot(guest_list.Get(), 25)(guest_list.Get(), guest_pipeline.Get()); + + // Slot 33: SetComputeRootSignature + using RootFn = void (WINAPI*)(IUnknown*, IUnknown*); + slot(guest_list.Get(), 33)(guest_list.Get(), guest_root.Get()); + + // Negative control 3: Dispatch with pipeline & root bound, but NO root arguments bound + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // 7. Test Root UAV (Slot 45) controls and PIN MUTANT: unset constants + using UavFn = void (WINAPI*)(IUnknown*, UINT, D3D12_GPU_VIRTUAL_ADDRESS); + const u64 guest_base_va = reinterpret_cast(guest_mem); + const u64 guest_subrange_va_128 = guest_base_va + 128; + const u64 guest_subrange_va_256 = guest_base_va + 256; + const u64 guest_subrange_va_384 = guest_base_va + 384; + + // Control UAV-A: Bind valid UAV pointing to +128 on param 0, but constants (param 1) are UNSET + // If a mutant relaxes the constants check, this dispatch executes and corrupts sentinel 0x33333333 at +128! + slot(guest_list.Get(), 45)(guest_list.Get(), 0, guest_subrange_va_128); + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // Control UAV-B: Slot 45 with wrong parameter type (param 1 is 32-bit constants, not UAV) -> dropped + slot(guest_list.Get(), 45)(guest_list.Get(), 1, guest_subrange_va_256); + + // Control UAV-C: Slot 45 with out-of-range parameter (param 2, root has 2 parameters) -> dropped + slot(guest_list.Get(), 45)(guest_list.Get(), 2, guest_subrange_va_256); + + // Control UAV-Param16: Slot 45 with parameter 16 (parameter >= 16 guard) -> dropped + slot(guest_list.Get(), 45)(guest_list.Get(), 16, guest_subrange_va_256); + + // Control UAV-Unplaced: Slot 45 with unplaced host memory -> not bound as GPU address, clears binding + void* unplaced_mem = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (unplaced_mem) { + slot(guest_list.Get(), 45)(guest_list.Get(), 0, reinterpret_cast(unplaced_mem)); + VirtualFree(unplaced_mem, 0, MEM_RELEASE); + } + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // 8. Test Root Constants (32 constants, range checking, out-of-range write controls): + using ConstantsFn = void (WINAPI*)(IUnknown*, UINT, UINT, const void*, UINT); + using ConstantFn = void (WINAPI*)(IUnknown*, UINT, UINT, UINT); + std::vector constants_32(33, 0); + constants_32[0] = 3; // scale = 3 + constants_32[1] = 7; // bias = 7 + constants_32[31] = 2; // extra = 2 (in DWORD 31, offset 124) + + // Control Const-A: Slot 39/37 on wrong parameter type (param 0 is UAV, not constants) -> dropped + slot(guest_list.Get(), 39)(guest_list.Get(), 0, 1, constants_32.data(), 0); + slot(guest_list.Get(), 37)(guest_list.Get(), 0, 5, 0); + + // Control Const-B: Slot 39/37 on out-of-range parameter (param 2) -> dropped + slot(guest_list.Get(), 39)(guest_list.Get(), 2, 1, constants_32.data(), 0); + slot(guest_list.Get(), 37)(guest_list.Get(), 2, 5, 0); + + // Control Const-Param16: Slot 39/37 on parameter 16 -> dropped + slot(guest_list.Get(), 39)(guest_list.Get(), 16, 1, constants_32.data(), 0); + slot(guest_list.Get(), 37)(guest_list.Get(), 16, 5, 0); + + // Control Const-Partial: write only words 0, 1 and 31, leaving words 2-30 unbound. The Dispatch must be + // refused; a mutant that checks only word 0 forwards it, and the shader (which reads only words 0, 1 and 31) + // writes 39 into the sentinel at offset 64. + const u64 guest_subrange_va_64 = guest_base_va + 64; + slot(guest_list.Get(), 45)(guest_list.Get(), 0, guest_subrange_va_64); + slot(guest_list.Get(), 39)(guest_list.Get(), 1, 2, constants_32.data(), 0); + slot(guest_list.Get(), 37)(guest_list.Get(), 1, 2, 31); + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // Out-of-range negative controls on parameter 1: + // Control Const-C: count exceeds parameter bound (count 33) -> cut to the 32 words both sides keep. + // Bind a UAV with its own target first: this Dispatch must see the same 32 words on the desktop list, so a + // store that marks all 32 words bound while the forward is skipped would write 0 here instead of 39. + const u64 guest_subrange_va_448 = guest_base_va + 448; + slot(guest_list.Get(), 45)(guest_list.Get(), 0, guest_subrange_va_448); + slot(guest_list.Get(), 39)(guest_list.Get(), 1, 33, constants_32.data(), 0); + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + // Control Const-D: offset exceeds parameter bound (offset 32) -> rejected + slot(guest_list.Get(), 39)(guest_list.Get(), 1, 1, constants_32.data(), 32); + slot(guest_list.Get(), 37)(guest_list.Get(), 1, 999, 32); + // Control Const-E: offset + count exceeds parameter bound (offset 31, count 2) -> rejected + slot(guest_list.Get(), 39)(guest_list.Get(), 1, 2, constants_32.data(), 31); + + // Valid write of full 32 constants via Slot 39 + slot(guest_list.Get(), 39)(guest_list.Get(), 1, 32, constants_32.data(), 0); + + // Slot 37: SetComputeRoot32BitConstant(param=1, data=5, offset=0) -> updates scale to 5! + slot(guest_list.Get(), 37)(guest_list.Get(), 1, 5, 0); + + // PIN MUTANTS: slot 37's forward and its 32-word capacity. A dispatch here, before restore_compute_root, + // keeps the store's replay from masking the forward. The full slot 39 write above left scale=3, extra=2; + // slot 37 then wrote scale=5. Writing extra=4 through slot 37 must reach the desktop root list (word 31 + // needs the 32-word capacity). Expected 5 * 10 + 7 + 4 = 61 at offset 192. Without the forward the desktop + // list still has scale=3, extra=2 and reads 39; with the translated 8-word capacity extra stays 2 and it + // reads 59. Restore extra=2 afterwards so the restored dispatch at offset 256 below still expects 59. + const u64 guest_subrange_va_192 = guest_base_va + 192; + slot(guest_list.Get(), 45)(guest_list.Get(), 0, guest_subrange_va_192); + slot(guest_list.Get(), 37)(guest_list.Get(), 1, 4, 31); + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + slot(guest_list.Get(), 37)(guest_list.Get(), 1, 2, 31); + + // Control UAV-Upload: upload pages are read-only for shaders, so the bind is dropped and the Dispatch refused. + // A mutant that accepts it writes 59 into the page (and asks the GPU to write an upload heap). + using UploadFn = void* (WINAPI*)(IUnknown*, UINT64, UINT64); + void* const upload_target = slot(guest_list.Get(), 148)(guest_list.Get(), 64, 16); + if (!upload_target) return 13; + std::memset(upload_target, 0, 64); + slot(guest_list.Get(), 45)(guest_list.Get(), 0, reinterpret_cast(upload_target)); + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // Control UAV-NoUavFlag: a placed buffer without ALLOW_UNORDERED_ACCESS cannot be a UAV target. + void* const read_only_mem = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!read_only_mem) return 13; + std::memset(read_only_mem, 0, 4096); + const D3D12_RESOURCE_DESC read_only_desc{ + D3D12_RESOURCE_DIMENSION_BUFFER, 0, 4096, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE + }; + ComPtr read_only_wrapper; + if (FAILED(slot(guest.Get(), 133)(guest.Get(), read_only_mem, &read_only_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, &__uuidof(ID3D12Resource), + reinterpret_cast(read_only_wrapper.GetAddressOf())))) + return 13; + slot(guest_list.Get(), 45)(guest_list.Get(), 0, reinterpret_cast(read_only_mem)); + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // Control UAV-NotAliased: a copied placement is a desktop copy, not title memory, so a UAV bind there would + // lose the write. A mutant that binds the committed buffer writes 59 into it (read back below). + void* const copied_mem_base = VirtualAlloc(nullptr, 128 * 1024, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!copied_mem_base) return 13; + void* const copied_mem = static_cast(copied_mem_base) + 0x100; // not 64 KiB aligned: forces the committed fallback + const D3D12_RESOURCE_DESC copied_desc{ + D3D12_RESOURCE_DIMENSION_BUFFER, 0, 512, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + }; + ComPtr copied_wrapper; + if (FAILED(slot(guest.Get(), 133)(guest.Get(), copied_mem, &copied_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, &__uuidof(ID3D12Resource), + reinterpret_cast(copied_wrapper.GetAddressOf())))) + return 13; + const auto copied_res = native_object(probe.desktop.Get(), guest.Get(), copied_wrapper.Get()); + if (!copied_res) return 13; + slot(guest_list.Get(), 45)(guest_list.Get(), 0, reinterpret_cast(copied_mem)); + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // 9. PIN MUTANTS: Unset UAV, alignment, and placed.reject + // Bind valid UAV pointing to +384. Desktop list now holds UAV at +384! + slot(guest_list.Get(), 45)(guest_list.Get(), 0, guest_subrange_va_384); + + // Control UAV-Misaligned: Slot 45 with misaligned address (+1 byte). Clears binding in pass, + // but desktop list retains previous UAV at +384. + slot(guest_list.Get(), 45)(guest_list.Get(), 0, guest_subrange_va_384 + 1); + // Constants ARE bound. UAV is UNSET. + // If a mutant relaxes the UAV check, this dispatch executes and corrupts sentinel 0x44444444 at +384! + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // Rebind UAV at +384 + slot(guest_list.Get(), 45)(guest_list.Get(), 0, guest_subrange_va_384); + // Control UAV-Reject: Slot 45 with rejected placed range (~0u64). Clears binding in pass. + slot(guest_list.Get(), 45)(guest_list.Get(), 0, ~u64{0}); + // If a mutant ignores placed.reject, this dispatch executes and corrupts sentinel 0x44444444 at +384! + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // 10. Valid bindings & test restore_compute_root: + // Bind valid nonzero aligned subrange UAV at offset 256 + slot(guest_list.Get(), 45)(guest_list.Get(), 0, guest_subrange_va_256); + + // Simulate an intervening shim compute pass: it sets a root with the same layout and writes its own arguments + // through it (the indexed-draw validation writes 8 constants through the root it sets). Both the constants and the + // UAV are clobbered here, so a dispatch without the restore replay reads 0 at the wrong subrange. + ComPtr clobber_root; + if (FAILED(probe.desktop->CreateRootSignature(0, serialized_root->GetBufferPointer(), serialized_root->GetBufferSize(), + IID_PPV_ARGS(&clobber_root)))) return 13; + desktop_list->SetComputeRootSignature(clobber_root.Get()); + const UINT zero_constants[32]{}; + desktop_list->SetComputeRoot32BitConstants(1, 32, zero_constants, 0); + desktop_list->SetComputeRootUnorderedAccessView(0, placed_res->GetGPUVirtualAddress() + 384); + + // Restore the compute root signature, UAV, and all 32 root constants + if (!x2w_d3d12_fixture_restore_compute_root(guest_list.Get())) return 13; + + // 11. Execute Dispatch: Slot 14 Dispatch(1, 1, 1) -> all root arguments restored! + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // Control UAV-RootRoundTrip: slot 33 with null and the same root again clears the title's root arguments while + // the desktop root object stays the same. Every constant is rebound but slot 45 is not, so the Dispatch must be + // refused; a mutant that keeps the UAV recorded at +384 writes 39 over sentinel 0x44444444. + slot(guest_list.Get(), 45)(guest_list.Get(), 0, guest_subrange_va_384); + slot(guest_list.Get(), 33)(guest_list.Get(), nullptr); + slot(guest_list.Get(), 33)(guest_list.Get(), guest_root.Get()); + slot(guest_list.Get(), 39)(guest_list.Get(), 1, 32, constants_32.data(), 0); + slot(guest_list.Get(), 14)(guest_list.Get(), 1, 1, 1); + + // 12. Copy placed resource to readback buffer + transition(desktop_list.Get(), placed_res.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + desktop_list->CopyBufferRegion(readback_buffer.Get(), 0, placed_res.Get(), 0, 512); + transition(desktop_list.Get(), copied_res.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + desktop_list->CopyBufferRegion(copied_readback.Get(), 0, copied_res.Get(), 0, 512); + + // Close guest list (calls Close on desktop_list) + using CloseFn = HRESULT (WINAPI*)(IUnknown*); + if (FAILED(slot(guest_list.Get(), 9)(guest_list.Get()))) return 14; + + // Submit and synchronize + ID3D12CommandList* submitted[]{desktop_list.Get()}; + queue->ExecuteCommandLists(1, submitted); + if (FAILED(queue->Signal(fence.Get(), 1))) return 15; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (fence->GetCompletedValue() < 1) { + fence->SetEventOnCompletion(1, event); + WaitForSingleObject(event, 5000); + } + CloseHandle(event); + + // 13. Read back result and verify: + // Expected val = scale * (10 + group.x) + bias + extra = 5 * (10 + 0) + 7 + 2 = 59 written at subrange offset 256. + // Sentinel at offset 0 must remain 0x11111111. + // Sentinel at offset 64 must remain 0x66666666 (pins partial constants mutant). + // Sentinel at offset 128 must remain 0x33333333 (pins unset constants mutant). + // Sentinel at offset 384 must remain 0x44444444 (pins unset UAV / alignment mutant). + void* mapped = nullptr; + const D3D12_RANGE read_range{0, 512}; + if (FAILED(readback_buffer->Map(0, &read_range, &mapped))) return 16; + UINT sentinel_0 = 0; + UINT sentinel_64 = 0; + UINT sentinel_128 = 0; + UINT result_192 = 0; + UINT result_256 = 0; + UINT sentinel_384 = 0; + UINT result_448 = 0; + std::memcpy(&sentinel_0, mapped, sizeof(UINT)); + std::memcpy(&sentinel_64, reinterpret_cast(mapped) + 64, sizeof(UINT)); + std::memcpy(&sentinel_128, reinterpret_cast(mapped) + 128, sizeof(UINT)); + std::memcpy(&result_192, reinterpret_cast(mapped) + 192, sizeof(UINT)); + std::memcpy(&result_256, reinterpret_cast(mapped) + 256, sizeof(UINT)); + std::memcpy(&sentinel_384, reinterpret_cast(mapped) + 384, sizeof(UINT)); + std::memcpy(&result_448, reinterpret_cast(mapped) + 448, sizeof(UINT)); + readback_buffer->Unmap(0, nullptr); + UINT copied_value = 0; + if (SUCCEEDED(copied_readback->Map(0, &read_range, &mapped))) { + std::memcpy(&copied_value, mapped, sizeof(UINT)); + copied_readback->Unmap(0, nullptr); + } + + std::printf("sentinel at offset 0: 0x%08x (expected 0x11111111)\n", sentinel_0); + std::printf("sentinel at offset 64: 0x%08x (expected 0x66666666, pins partial constants mutant)\n", sentinel_64); + std::printf("sentinel at offset 128: 0x%08x (expected 0x33333333, pins unset constants mutant)\n", sentinel_128); + std::printf("slot 37 forward value at offset 192: %u (expected 61, scale=5, bias=7, extra=4)\n", result_192); + std::printf("subrange value at offset 256: %u (expected 59, scale=5, bias=7, extra=2)\n", result_256); + std::printf("sentinel at offset 384: 0x%08x (expected 0x44444444, pins unset UAV / alignment mutant)\n", sentinel_384); + std::printf("cut-write value at offset 448: %u (expected 39, scale=3, bias=7, extra=2)\n", result_448); + std::printf("non-aliased UAV target: %u (expected 0)\n", copied_value); + if (sentinel_0 != 0x11111111u) return 17; + if (sentinel_64 != 0x66666666u) return 25; + if (sentinel_128 != 0x33333333u) return 18; + if (result_192 != 61) return 26; + if (result_256 != 59) return 19; + if (sentinel_384 != 0x44444444u) return 20; + if (result_448 != 39) return 21; + // The two refused UAV targets must not have been written by the shader. + if (*static_cast(upload_target) != 0) return 22; + if (*static_cast(read_only_mem) != 0) return 23; + if (copied_value != 0) return 24; + + + // 13. Verify device health and debug layer + const HRESULT removed = probe.desktop->GetDeviceRemovedReason(); + const unsigned long long errors = debug_error_count.load(); + std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast(removed), + static_cast(errors)); + + // Release wrappers and free memory + copied_wrapper.Reset(); + VirtualFree(copied_mem_base, 0, MEM_RELEASE); + read_only_wrapper.Reset(); + VirtualFree(read_only_mem, 0, MEM_RELEASE); + placed_wrapper.Reset(); + VirtualFree(guest_mem, 0, MEM_RELEASE); + + return removed == S_OK && errors == 0 ? 0 : 70; +} diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 02b7c56c32..31912b0df6 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -63,6 +63,12 @@ void consume_retained_compute_root() { data.Store(0, retained_input.Load(0)); } +cbuffer RetainedConstant : register(b0) { uint retained_constant; }; +[numthreads(1,1,1)] +void consume_retained_compute_constant() { + data.Store(0, retained_constant); +} + [numthreads(1, 1, 1)] void write_left() { data.Store4(4, uint4(3, 1, 1, 0)); @@ -1350,13 +1356,22 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ ComPtr retained_result; ComPtr retained_readback; const UINT retained_value = draw_right ? 0xcafe0489 : 0x31ac1579; + // A rectangle conversion that is not refused replays the root constants through restore_compute_root. A recorded + // root view refuses the conversion (rect_live_compute), so that run keeps a 32-bit constant, not an uploaded SRV. + const bool retain_constant = kind == DrawKind::rect && refusal == Refusal::none; if (restore_compute) { D3D12_ROOT_PARAMETER params[2]{}; - params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + if (retain_constant) { + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants.Num32BitValues = 1; + } else { + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + } params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; retained_compute_root = create_root(guest, {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}); const auto native_root = native_object(device, guest, retained_compute_root.Get()); - retained_compute_pipeline = writer_pipeline(device, native_root.Get(), "consume_retained_compute_root"); + retained_compute_pipeline = writer_pipeline(device, native_root.Get(), + retain_constant ? "consume_retained_compute_constant" : "consume_retained_compute_root"); retained_result = make_buffer(device, 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); retained_readback = make_buffer(device, 4, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); @@ -1364,12 +1379,17 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ using Allocate = void* (WINAPI*)(IUnknown*, UINT64, UINT64); using Srv = void (WINAPI*)(IUnknown*, UINT, UINT64); slot(wrapped, 33)(wrapped, retained_compute_root.Get()); - auto* const input = static_cast(slot(wrapped, 148)(wrapped, 16, 16)); - if (!input) return false; - *input = retained_value; - slot(wrapped, 43)(wrapped, 0, reinterpret_cast(input)); - if (draw_right) slot(wrapped, 33)(wrapped, nullptr); - else if (kind == DrawKind::rect) slot(wrapped, 33)(wrapped, retained_compute_root.Get()); + if (retain_constant) { + using Constant = void (WINAPI*)(IUnknown*, UINT, UINT, UINT); + slot(wrapped, 37)(wrapped, 0, retained_value, 0); + } else { + auto* const input = static_cast(slot(wrapped, 148)(wrapped, 16, 16)); + if (!input) return false; + *input = retained_value; + slot(wrapped, 43)(wrapped, 0, reinterpret_cast(input)); + if (draw_right) slot(wrapped, 33)(wrapped, nullptr); + else if (kind == DrawKind::rect) slot(wrapped, 33)(wrapped, retained_compute_root.Get()); + } } const UINT64 offset = refusal == Refusal::short_argument ? sizeof(initial_words) - command_stride(kind) + sizeof(std::uint32_t) : indexed_argument_offset; @@ -1380,7 +1400,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ fixed_source_heap.Reset(); fixed_heap_resource.Reset(); if (restore_compute) { - // Leave the previously forwarded root + SRV alone. Only install the + // Leave the previously forwarded root arguments alone. Only install the // consumer PSO and the output UAV that this fixture owns. transition(list, retained_result.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list->SetPipelineState(retained_compute_pipeline.Get()); @@ -1442,7 +1462,8 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ std::fprintf(stderr, "restored compute readback=%08x expected=%08x\n", actual, retained_value); return false; } - std::printf("restored compute root and one uploaded SRV: GPU readback %08x\n", actual); + std::printf("restored compute root and one %s: GPU readback %08x\n", + retain_constant ? "root constant" : "uploaded SRV", actual); } if (translated) { constexpr Words empty{}; @@ -3899,6 +3920,9 @@ int main(int argc, char** argv) try !run(device.Get(), guest.Get(), writer.Get(), overflow.Get(), graphics.Get(), pso.Get(), signature.Get(), kind, false, Refusal::overflowing_count, "overflowing rectangle count")) return 1; if (kind == DrawKind::rect) { + if (!run(device.Get(), guest.Get(), writer.Get(), left.Get(), graphics.Get(), pso.Get(), signature.Get(), kind, + false, Refusal::none, "rectangle conversion restores compute constants", nullptr, false, nullptr, + false, false, 0, false, true)) return 1; if (!run(device.Get(), guest.Get(), writer.Get(), left.Get(), graphics.Get(), pso.Get(), signature.Get(), kind, false, Refusal::rect_live_compute, "rectangle with rebound compute root", nullptr, false, nullptr, false, false, 0, false, true) || diff --git a/tests/startup_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp index 17abf36480..633f0b8a42 100644 --- a/tests/startup_list_dispatch_check.cpp +++ b/tests/startup_list_dispatch_check.cpp @@ -58,7 +58,7 @@ int main(int argc, char** argv) d.compute_root = false; expect("no compute root", d, no_state ? D::forward : D::no_compute_state); d = ready(8, 1, 1); - d.compute_root_has_arguments = true; // e.g. a root UAV set through slot 45, which is not forwarded + d.compute_root_has_arguments = true; // e.g. a root CBV or unforwarded table parameter expect("root with arguments", d, no_root_args ? D::forward : D::unforwarded_root_arguments); d.x = 0; expect("root with arguments, zero groups", d, no_root_args ? D::forward : D::unforwarded_root_arguments); diff --git a/tests/startup_list_dispatch_native.cpp b/tests/startup_list_dispatch_native.cpp index 25586fde22..64ffb63b87 100644 --- a/tests/startup_list_dispatch_native.cpp +++ b/tests/startup_list_dispatch_native.cpp @@ -201,19 +201,19 @@ class Fixture { // Recording 2: each refusal after a fresh Close, so no binding is left over from recording 1. reset(); - ok = expect({"root SRV never set", 3, 1, 1, "a compute root SRV is not bound", 0}, + ok = expect({"root SRV never set", 3, 1, 1, "a compute root argument is not bound", 0}, [&] { bind(pso_a_.Get(), root_a_.Get()); }); - ok = ok && expect({"rejected replacement after a valid root SRV", 4, 1, 1, "a compute root SRV is not bound", 1}, [&] { + ok = ok && expect({"rejected replacement after a valid root SRV", 4, 1, 1, "a compute root argument is not bound", 1}, [&] { bind(pso_a_.Get(), root_a_.Get()); srv(upload_); srv(reinterpret_cast(&foreign_)); // not in this recording's upload pages }); - ok = ok && expect({"misaligned replacement after a valid root SRV", 5, 1, 1, "a compute root SRV is not bound", 2}, [&] { + ok = ok && expect({"misaligned replacement after a valid root SRV", 5, 1, 1, "a compute root argument is not bound", 2}, [&] { bind(pso_a_.Get(), root_a_.Get()); srv(upload_); srv(upload_ + 2); // in the upload pages, not 4-byte aligned }); - ok = ok && expect({"root changed and changed back", 6, 1, 1, "a compute root SRV is not bound", 3}, [&] { + ok = ok && expect({"root changed and changed back", 6, 1, 1, "a compute root argument is not bound", 3}, [&] { bind(pso_a_.Get(), root_a_.Get()); srv(upload_); root(root_b_.Get()); @@ -228,7 +228,7 @@ class Fixture { [&] { bind(pso_table_.Get(), root_table_.Get()); }); ok = ok && expect({"root with a static sampler", 9, 1, 1, "compute root arguments are not forwarded", 6}, [&] { bind(pso_sampler_.Get(), root_sampler_.Get()); }); - ok = ok && expect({"root SRV never set, zero groups", 0, 10, 1, "a compute root SRV is not bound", 7}, + ok = ok && expect({"root SRV never set, zero groups", 0, 10, 1, "a compute root argument is not bound", 7}, [&] { bind(pso_a_.Get(), root_a_.Get()); }); ok = ok && expect({"bound, X over the limit", 65536, 1, 1, "group count is over 65535", 8}, [&] { bind(pso_a_.Get(), root_a_.Get()); diff --git a/tests/startup_root_constant_store.cpp b/tests/startup_root_constant_store.cpp index a07bb3acf1..ab32e11a14 100644 --- a/tests/startup_root_constant_store.cpp +++ b/tests/startup_root_constant_store.cpp @@ -52,6 +52,24 @@ int main() expect(store.set_one(1, 0, 0) == Result::stored && store.is_bound(1, 0, 1) && store.word(1, 0) == 0, "writing 0 is set, unlike never written"); + // Capacity up to 32 words for native slot 86 root constants: + std::uint32_t data32[32]{}; + for (unsigned i = 0; i < 32; ++i) data32[i] = i * 10; + expect(store.set(1, 32, data32, 0, 32) == Result::stored, "32 words stored with capacity 32"); + expect(store.is_bound(1, 0, 32, 32), "all 32 words bound with capacity 32"); + expect(store.word(1, 31) == 310, "last word reads back"); + expect(store.set(1, 1, data32, 32, 32) == Result::dropped, "offset 32 dropped with capacity 32"); + expect(store.set(1, 2, data32, 31, 32) == Result::truncated, "offset 31 count 2 truncated with capacity 32"); + + // A full 32-word range with its last word unset is not bound: the mask for a full-width range must not wrap to 0. + expect(store.set(9, 31, data32, 0, 32) == Result::stored, "31 words stored with capacity 32"); + expect(!store.is_bound(9, 0, 32, 32), "a 32-word range whose last word is unset is not bound"); + expect(store.is_bound(9, 0, 31, 32), "the 31 written words are bound"); + + // A capacity above the kept maximum is refused by both the store and the bound test. + expect(store.set(9, 1, data32, 0, 33) == Result::dropped, "a capacity above 32 is refused"); + expect(!store.is_bound(9, 0, 31, 33), "a capacity above 32 is never bound"); + store.clear(); expect(store.word(3, 2) == 0 && store.word(15, 0) == 0, "clear zeroes every word"); expect(!store.is_bound(3, 2, 4) && !store.is_bound(1, 0, 1), "clear forgets which words were set");