diff --git a/docs/experiments/startup-compute-builder-gate.md b/docs/experiments/startup-compute-builder-gate.md new file mode 100644 index 0000000000..a1734ef25d --- /dev/null +++ b/docs/experiments/startup-compute-builder-gate.md @@ -0,0 +1,59 @@ +# All-or-none gate for the BVH builder's compute stages + +The console ray-tracing structure builder is a set of compute programs from `XboxBvhBuilder.dll`. +Its stages feed each other through title memory; a stage that runs on data a missing stage never +wrote computes store offsets from garbage. In the observed failure, 14 of 35 translated stages ran +and the title died within a second on pointers that had become bounding-box bit patterns. + +`X2W_COMPUTE_BUILDER_GATE=1` makes the set run all or none. It is off by default and changes no +existing path when unset. + +## Identification + +At device slot 62, the gate resolves the caller module of the return address with +`GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)` and compares the basename with +`XboxBvhBuilder.dll`, case-insensitively. A compute pipeline is tracked only when that resolution +succeeds; an unresolved caller is left untracked rather than guessed. The header's pure classifier +and state machine are tested without a device or a title module. + +## Decision + +A builder Dispatch is allowed when every tracked builder pipeline has a real desktop PSO. On the +first builder Dispatch the gate makes the missing pipelines on the spot. If one cannot be made, the +builder is turned off for the rest of the run and the Dispatch is refused with a named reason. A +non-builder Dispatch is unchanged. The gate is keyed on the slot 62 wrapper's builder tag, not on +`compute_request_key`: slot 67 never receives that tag, so its request publication path is +unchanged. The gate is counted in the compute totals line as `builder gate refused N`. + +When the gate completes the set it also refreshes the recording's cached compute state +(`pipeline_real`, `compute_pipeline`, `compute_pipeline_root`) and binds the new desktop PSO, and +the matching desktop root when the title already bound it. Without that refresh the caller's own +`Dispatch` decision still sees the placeholder that was bound before the gate ran and drops the +first Dispatch. + +## Scope and limits + +This is a safety gate, not a translation. The slot 62 programs are console GPU code; the gate's +on-the-spot creation first requires a structurally valid desktop compute container and a desktop +root signature. A console DXIL program fails by name and latches the builder off, which is the +intended conservative result until the translation path publishes real compute PSOs. + +The runtime test loads a source-built `XboxBvhBuilder.dll` helper and calls the public slot 62 +path through it. In the incomplete-set mode two fake console pipelines are tracked, a direct +`Dispatch` and an indirect `ExecuteIndirect` are both refused with the gate enabled, and the same +direct call through a non-builder slot 62 wrapper is left untouched. In the completed-set mode two +desktop DXIL compute shaders are tracked, the gate reports `all have a desktop PSO`, and the first +direct `Dispatch` plus an indirect `ExecuteIndirect` with a placed argument buffer reach the list. +A separate run of the existing slot 67 request check with `X2W_COMPUTE_BUILDER_GATE=1` passes, so +request publication keeps its normal path. + +The helper test proves the caller-module tag, the wiring into both public Dispatch paths, and the +completed-set refresh on source-built desktop DXIL. It does not prove a translated builder set from +the title; the fake console container still fails desktop PSO creation by name and latches the +builder off, which is the intended conservative result. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_compute_builder_gate$' -V +ctest --preset dev --no-tests=error -R '^startup_compute_builder_gate_runtime$' -V +ctest --preset dev --no-tests=error -R '^startup_compute_builder_gate_request_warp$' -V +``` diff --git a/src/startup_stubs/compute_builder_gate.h b/src/startup_stubs/compute_builder_gate.h new file mode 100644 index 0000000000..9daab86150 --- /dev/null +++ b/src/startup_stubs/compute_builder_gate.h @@ -0,0 +1,147 @@ +#pragma once + +// Opt-in all-or-none gate for the console BVH builder's compute pipeline set +// (X2W_COMPUTE_BUILDER_GATE=1). Pure helpers and state, with no Windows calls, so a source-built +// control can check the decision without a device or a title module. +// +// A builder pipeline is a compute pipeline created through device slot 62 whose caller module is +// XboxBvhBuilder.dll. A builder Dispatch is allowed only while every tracked builder pipeline has a +// real desktop pipeline state. The first builder Dispatch attempts the missing creations; one failure +// latches the builder off for the rest of the process, so a partial builder cannot write through +// root views into title memory. + +#include +#include +#include +#include + +namespace x2w_startup { + +// The basename of a module path, case-insensitive and accepting either slash. The console builder +// is the only module whose slot 62 compute pipelines this gate tracks. +inline bool is_compute_builder_module(std::wstring_view path) noexcept +{ + constexpr wchar_t expected[] = L"XboxBvhBuilder.dll"; + constexpr std::size_t expected_size = sizeof(expected) / sizeof(expected[0]) - 1; + const std::size_t slash = path.find_last_of(L"\\/"); + const std::wstring_view base = slash == std::wstring_view::npos ? path : path.substr(slash + 1); + if (base.size() != expected_size) return false; + for (std::size_t i = 0; i < expected_size; ++i) { + wchar_t got = base[i]; + wchar_t want = expected[i]; + if (got >= L'A' && got <= L'Z') got = static_cast(got - L'A' + L'a'); + if (want >= L'A' && want <= L'Z') want = static_cast(want - L'A' + L'a'); + if (got != want) return false; + } + return true; +} + +enum class BuilderGateDecision : std::uint8_t { + unchanged, // gate off, or the Dispatch does not use a tracked builder pipeline + allow, // every tracked builder pipeline has a desktop PSO + refuse_missing, // at least one tracked builder pipeline has no desktop PSO; the caller may attempt creation + refuse_off, // a creation failed earlier; the builder stays off for the rest of the run +}; + +class BuilderGateState { +public: + // 52 builder programs were observed in the inspected module. The margin leaves room for a + // second creation pass without ever allowing an untracked pipeline into the all-or-none set. + static constexpr unsigned max_pipelines = 64; + + explicit BuilderGateState(bool enabled = false) noexcept : enabled_(enabled) {} + + bool enabled() const noexcept { return enabled_; } + bool off() const noexcept { return off_; } + unsigned tracked() const noexcept { return tracked_; } + unsigned with_pso() const noexcept { return with_pso_; } + unsigned refusals() const noexcept { return refusals_; } + const char* first_reason() const noexcept { return reason_; } + + // Records a slot 62 creation. Only builder pipelines are tracked; a non-builder one changes + // nothing. A repeated pointer updates its state instead of adding an entry. Returns false when + // the builder set cannot be tracked completely, in which case the gate latches off. + bool note_pipeline(const void* pipeline, bool builder, bool real) noexcept + { + if (!enabled_ || !builder || !pipeline) return true; + for (unsigned i = 0; i < tracked_; ++i) { + if (entries_[i].pipeline != pipeline) continue; + if (entries_[i].real != real) { + if (real) ++with_pso_; + else --with_pso_; + entries_[i].real = real; + } + return true; + } + if (tracked_ == max_pipelines) { + note_failed("builder pipeline table is full"); + return false; + } + entries_[tracked_++] = Entry{pipeline, real}; + if (real) ++with_pso_; + return true; + } + + // Marks one tracked pipeline as having a real desktop PSO after an on-the-spot creation. + void note_pso(const void* pipeline) noexcept + { + if (!enabled_ || !pipeline) return; + for (unsigned i = 0; i < tracked_; ++i) { + if (entries_[i].pipeline != pipeline || entries_[i].real) continue; + entries_[i].real = true; + ++with_pso_; + return; + } + } + + // Latches the builder off. The pointer must name a static string; it is reported later. + void note_failed(const char* reason) noexcept + { + if (!enabled_ || off_) return; + off_ = true; + reason_ = reason ? reason : "builder pipeline creation failed"; + } + + // The next pipeline without a desktop PSO at or after index. A real entry yields nullptr, so + // callers can walk the whole table while note_pso updates it. + const void* missing_at(unsigned index) const noexcept + { + return index < tracked_ && !entries_[index].real ? entries_[index].pipeline : nullptr; + } + + BuilderGateDecision decide(bool builder_dispatch) const noexcept + { + if (!enabled_ || !builder_dispatch) return BuilderGateDecision::unchanged; + if (off_) return BuilderGateDecision::refuse_off; + if (tracked_ && with_pso_ == tracked_) return BuilderGateDecision::allow; + return BuilderGateDecision::refuse_missing; + } + + void note_refusal() noexcept { ++refusals_; } + +private: + struct Entry { + const void* pipeline = nullptr; + bool real = false; + }; + std::array entries_{}; + unsigned tracked_ = 0; + unsigned with_pso_ = 0; + unsigned refusals_ = 0; + bool enabled_ = false; + bool off_ = false; + const char* reason_ = nullptr; +}; + +inline const char* builder_gate_reason(BuilderGateDecision decision) noexcept +{ + switch (decision) { + case BuilderGateDecision::unchanged: return "unchanged"; + case BuilderGateDecision::allow: return "allow"; + case BuilderGateDecision::refuse_missing: return "not every builder pipeline has a desktop pipeline"; + case BuilderGateDecision::refuse_off: return "the builder is off for the rest of the run"; + } + return "unknown"; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 9976d39e39..3204f0f6fd 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -33,6 +33,7 @@ #include "startup_stubs/indexed_indirect_guard.h" #include "startup_stubs/indexed_rect_geometry.h" #include "startup_stubs/list_dispatch.h" +#include "startup_stubs/compute_builder_gate.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" #include "startup_stubs/address_texture.h" @@ -187,6 +188,8 @@ struct alignas(16) WrapperOwn { u64 retire_written_gen; // Snapshotted written_textures() generation for stale-entry cleanup. bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline + bool builder_pipeline; // PipelineState: slot 62 created it for XboxBvhBuilder.dll (X2W_COMPUTE_BUILDER_GATE) + x2w_startup::BuilderGateState* compute_builder_gate; // Device: tracked builder pipelines, or null until needed u64 compute_trace_key; // Opt-in trace: selected slot 62 container hash const void* compute_trace_root; LONG compute_trace_dispatches; @@ -2879,6 +2882,8 @@ struct Pass { std::vector ended_queries; }; LONG render_draws, render_draws_skipped, render_pipelines_real, render_pipelines_missing; +LONG compute_builder_gate_refusals; // builder Dispatches refused by X2W_COMPUTE_BUILDER_GATE +SRWLOCK compute_builder_lock = SRWLOCK_INIT; // Heap-indexed title root signatures not set on the desktop list, and real draws refused under one, by decision. LONG heap_roots_deferred, heap_root_refusals[x2w_startup::real_root_decision_count]; @@ -2889,6 +2894,210 @@ Pass& pass_of(Wrapper* self) return *static_cast(self->own().pass); } +bool compute_builder_gate_enabled() +{ + static const bool on = x2w_local::env_on("X2W_COMPUTE_BUILDER_GATE"); + return on; +} + +// The module holding the slot 62 return address. GetModuleHandleExW with FROM_ADDRESS is the same +// resolution RtlPcToFileHeader performs, is safe for any pointer and leaves no module reference. +bool compute_builder_caller_module(const void* return_address) noexcept +{ + if (!return_address) return false; + const DWORD saved = GetLastError(); + HMODULE module = nullptr; + bool matches = false; + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(return_address), &module) && module) { + std::wstring path(MAX_PATH, L'\0'); + for (;;) { + const DWORD length = GetModuleFileNameW(module, path.data(), static_cast(path.size())); + if (!length) break; + if (length < path.size()) { + matches = x2w_startup::is_compute_builder_module(std::wstring_view(path.data(), length)); + break; + } + if (path.size() >= 32768) break; // longer than any supported Windows path + path.resize(path.size() * 2); + } + } + SetLastError(saved); + return matches; +} + +x2w_startup::BuilderGateState* compute_builder_gate_for(Wrapper* device) +{ + if (!device || device->own().kind != device_kind) return nullptr; + if (!device->own().compute_builder_gate) { + auto* gate = new (std::nothrow) x2w_startup::BuilderGateState(true); + if (gate) device->own().compute_builder_gate = gate; + } + return device->own().compute_builder_gate; +} + +// A structurally valid desktop DXIL compute container. Console DXBC containers (the 52 builder +// programs) have a console DXIL target, so they are refused here instead of being submitted. +const char* desktop_compute_program_reason(const D3D12_SHADER_BYTECODE& code) noexcept +{ + if (!readable_shader_container(code)) return "the console compute program is missing or unreadable"; + const auto* data = static_cast(code.pShaderBytecode); + const auto word = [data](std::size_t offset) { + UINT value; + std::memcpy(&value, data + offset, sizeof(value)); + return value; + }; + const std::size_t bytes = code.BytecodeLength; + if (bytes < 32 || word(24) != bytes) return "the console compute container is malformed"; + const std::size_t parts = word(28); + if (parts > (bytes - 32) / 4) return "the console compute container is malformed"; + const std::size_t header = 32 + parts * 4; + bool found = false; + for (std::size_t i = 0; i < parts; ++i) { + const std::size_t part = word(32 + i * 4); + if (part < header || part > bytes - 8) return "the console compute container is malformed"; + const std::size_t size = word(part + 4); + if (size > bytes - part - 8) return "the console compute container is malformed"; + if (std::memcmp(data + part, "DXIL", 4)) continue; + if (found) return "the console compute container has more than one DXIL part"; + found = true; + const std::size_t program = part + 8; + if (size < 24 || word(program) >> 16 != D3D12_SHVER_COMPUTE_SHADER) return "the DXIL program is not a compute shader"; + const std::size_t bitcode = word(program + 16); + const std::size_t bitcode_size = word(program + 20); + if (word(program + 4) * 4ull != size || std::memcmp(data + program + 8, "DXIL", 4) || bitcode < 16 || + bitcode > size - 8 || bitcode_size < 4 || bitcode_size > size - 8 - bitcode || + std::memcmp(data + program + 8 + bitcode, "BC\xc0\xde", 4)) + return "the DXIL program is malformed"; + } + return found ? nullptr : "the console compute program is not desktop DXIL"; +} + +// The on-the-spot creation for one tracked builder pipeline. This task has no translation step: a +// console program fails by name before reaching D3D12. A future translation can attach its desktop +// pipeline through the same entry point. +bool make_compute_builder_pipeline(Wrapper* device, Wrapper* pipeline, const char** reason) noexcept +{ + if (reason) *reason = nullptr; + if (!device || !pipeline || pipeline->own().kind != pipeline_kind) { + if (reason) *reason = "the tracked object is not a pipeline"; + return false; + } + if (pipeline->own().real) return true; + const PipelineInfo* info = pipeline_info(pipeline); + if (!info || info->path != 62 || info->desc.size() < sizeof(D3D12_COMPUTE_PIPELINE_STATE_DESC)) { + if (reason) *reason = "the slot 62 description is unavailable"; + return false; + } + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + std::memcpy(&desc, info->desc.data(), sizeof(desc)); + if (const char* program_reason = desktop_compute_program_reason(desc.CS)) { + if (reason) *reason = program_reason; + return false; + } + Wrapper* root = as_wrapper(desc.pRootSignature); + if (!root || root->own().kind != root_signature_kind || !root->own().real) { + if (reason) *reason = "the builder root signature has no desktop object"; + return false; + } + desc.pRootSignature = static_cast(root->own().real); + x2w_startup::ComPtr created; + const HRESULT hr = device_of(device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(created.GetAddressOf())); + if (FAILED(hr)) { + static LONG logged; + if (first_calls(logged, 4)) + log("x2w-render compute builder gate: desktop pipeline creation failed 0x%08lx", hr); + if (reason) *reason = "desktop pipeline creation failed"; + return false; + } + pipeline->own().real = created.Detach(); + pipeline->own().compute_pipeline = true; + pipeline->own().pipeline_root = desc.pRootSignature; + return true; +} + +void note_compute_builder_pipeline(Wrapper* device, Wrapper* pipeline, const void* return_address) +{ + if (!compute_builder_gate_enabled() || !device || !pipeline) return; + if (!compute_builder_caller_module(return_address)) return; + pipeline->own().builder_pipeline = true; + AcquireSRWLockExclusive(&compute_builder_lock); + x2w_startup::BuilderGateState* gate = compute_builder_gate_for(device); + if (!gate) { + static LONG logged; + if (first_calls(logged, 1)) log("x2w-render compute builder gate: no gate state; builder pipelines stay untracked"); + } else { + gate->note_pipeline(pipeline, true, pipeline->own().real != nullptr); + } + ReleaseSRWLockExclusive(&compute_builder_lock); +} + +// Called before the normal Dispatch path. It returns true for a non-builder Dispatch, for the gate +// being off, or when every tracked builder pipeline has a desktop PSO. A refusal has already been +// counted and logged once. +bool compute_builder_dispatch_allowed(Wrapper* list, const char* stage) +{ + if (!compute_builder_gate_enabled() || !list) return true; + Pass& pass = pass_of(list); + if (!pass.pipeline || !pass.pipeline->own().builder_pipeline) return true; + Wrapper* device = list->own().list_device; + AcquireSRWLockExclusive(&compute_builder_lock); + x2w_startup::BuilderGateState* gate = compute_builder_gate_for(device); + if (!gate) { + InterlockedIncrement(&compute_builder_gate_refusals); + static LONG logged; + if (first_calls(logged, 1)) + log("x2w-render compute builder gate: %s refused; no gate state is available", stage); + ReleaseSRWLockExclusive(&compute_builder_lock); + return false; + } + x2w_startup::BuilderGateDecision decision = gate->decide(true); + if (decision == x2w_startup::BuilderGateDecision::refuse_missing && gate->tracked() == 0) + gate->note_failed("no builder pipeline was tracked"); + if (decision == x2w_startup::BuilderGateDecision::refuse_missing) { + for (unsigned i = 0; i < gate->tracked(); ++i) { + const void* missing = gate->missing_at(i); + if (!missing) continue; + const char* reason = nullptr; + if (!make_compute_builder_pipeline(device, const_cast(static_cast(missing)), &reason)) { + gate->note_failed(reason); + break; + } + gate->note_pso(missing); + } + decision = gate->decide(true); + } + if (decision == x2w_startup::BuilderGateDecision::allow) { + // The title bound a placeholder wrapper earlier; the gate has just published its real + // desktop PSO. Refresh the recording's cached compute state and bind the PSO so the + // caller's Dispatch decision sees the completed pipeline instead of the placeholder. + if (auto* host = recording(list); host && pass.pipeline && pass.pipeline->own().real) { + pass.pipeline_real = true; + pass.compute_pipeline = true; + pass.compute_pipeline_root = pass.pipeline->own().pipeline_root; + host->SetPipelineState(static_cast(pass.pipeline->own().real)); + if (pass.compute_root && pass.compute_pipeline_root == pass.compute_root) + host->SetComputeRootSignature(pass.compute_root); + } + static LONG logged; + if (first_calls(logged, 1)) + log("x2w-render compute builder gate: %u tracked pipelines, all have a desktop PSO; %s allowed", + gate->tracked(), stage); + ReleaseSRWLockExclusive(&compute_builder_lock); + return true; + } + gate->note_refusal(); + InterlockedIncrement(&compute_builder_gate_refusals); + static LONG logged; + if (first_calls(logged, 1)) { + const char* reason = gate->first_reason(); + log("x2w-render compute builder gate: %u tracked pipelines, %u with a desktop PSO; %s refused: %s", + gate->tracked(), gate->with_pso(), stage, reason ? reason : "not every builder pipeline has a desktop PSO"); + } + ReleaseSRWLockExclusive(&compute_builder_lock); + return false; +} + bool indirect_copy_ranges() { static const bool enabled = x2w_local::env_on("X2W_TRANSLATED_INDIRECT_COPY_RANGES"); @@ -3318,6 +3527,7 @@ constexpr const char* count_missing_resource = "count_missing_resource"; constexpr const char* count_invalid_offset = "count_invalid_offset"; constexpr const char* count_outside_placed_buffer = "count_outside_placed_buffer"; constexpr const char* count_not_common_state = "count_not_common_state"; +constexpr const char* builder_gate = "builder_gate"; constexpr const char* unknown = "unknown"; } // namespace indirect_other_refusal_code @@ -3380,6 +3590,12 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const bool graphics = indexed || mesh || command == IndirectCommand::draw; Pass& pass = pass_of(self); refusal_pipeline = pass.pipeline; + // A slot 62 builder pipeline is tracked by the wrapper itself, not by a slot 67 request key. + // Gate its indirect Dispatch before the signature and argument checks so a partial builder + // cannot reach ExecuteIndirect. + if (command == IndirectCommand::dispatch && pass.pipeline && pass.pipeline->own().builder_pipeline && + !compute_builder_dispatch_allowed(self, "ExecuteIndirect")) + return refuse("the compute builder gate refused the Dispatch", indirect_compute_pipeline, indirect_other_refusal_code::builder_gate); const bool translated_compute = command == IndirectCommand::dispatch && pass.pipeline && pass.pipeline->own().compute_request_key; const bool translated = (command == IndirectCommand::draw || indexed) && pass.pipeline && !pass.pipeline->own().real && (pass.graphics_root || pass.deferred_root) && x2w_local::env_on("X2W_TRANSLATED_INDIRECT_DRAW"); @@ -4182,6 +4398,10 @@ void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) { auto* list = recording(self); const Pass& pass = pass_of(self); + // Slot 62 marks the wrapper itself. Slot 67 has no builder tag, so its request path is + // unchanged; a builder Dispatch is gated here regardless of the request-key field. + if (list && pass.pipeline && pass.pipeline->own().builder_pipeline && + !compute_builder_dispatch_allowed(self, "Dispatch")) return; if (list && pass.pipeline && pass.pipeline->own().compute_request_key) { record_translated_dispatch(self, {{x, y, z}}); return; @@ -6454,7 +6674,7 @@ HRESULT __stdcall placeholder_ok(Wrapper*, u64, u64, u64) { return S_OK; } // XboxBvhBuilder.dll, followed by SetName on the result. The bytecode is console GPU code, not DXIL, // so no desktop pipeline is built: the result is a placeholder PipelineState until shader translation // exists. Logs the root signature, bytecode address, length and first 32 bytes. -HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, u64 extra0, +HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, u64 extra0, u64 extra1, const GUID* iid, void** out) { char text[48]; @@ -6476,6 +6696,7 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE auto* pipeline = static_cast(*out); note_pipeline(pipeline, 62, nullptr, desc, sizeof(*desc)); note_compute_binding_pipeline(pipeline, *desc); + note_compute_builder_pipeline(self, pipeline, _ReturnAddress()); return S_OK; } @@ -7084,8 +7305,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); if (render_mode() && frame % 300 == 0) { - log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld", - compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled); + log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld, builder gate refused %ld", + compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled, + compute_builder_gate_refusals); log_compute_census(); } if (render_mode() && frame % 300 == 0) { diff --git a/tests/cmake/startup_compute_builder_gate.cmake b/tests/cmake/startup_compute_builder_gate.cmake new file mode 100644 index 0000000000..6370ce4dcb --- /dev/null +++ b/tests/cmake/startup_compute_builder_gate.cmake @@ -0,0 +1,39 @@ +# All-or-none gate for the console BVH builder's compute pipeline set +# (src/startup_stubs/compute_builder_gate.h), without a device or a title module. +add_executable(startup_compute_builder_gate_check tests/startup_compute_builder_gate_check.cpp) +target_include_directories(startup_compute_builder_gate_check PRIVATE src) +target_compile_features(startup_compute_builder_gate_check PRIVATE cxx_std_17) +add_test(NAME startup_compute_builder_gate COMMAND startup_compute_builder_gate_check) + +# A source-built module whose basename matches XboxBvhBuilder.dll, so the public slot 62 path can +# exercise the caller-module tag and the direct/indirect Dispatch gate. +add_library(startup_builder_module SHARED tests/startup_builder_module.cpp) +set_target_properties(startup_builder_module PROPERTIES OUTPUT_NAME XboxBvhBuilder) +target_compile_features(startup_builder_module PRIVATE cxx_std_17) +target_link_libraries(startup_builder_module PRIVATE d3d12) + +add_executable(startup_compute_builder_gate_runtime tests/startup_compute_builder_gate_runtime.cpp) +target_compile_features(startup_compute_builder_gate_runtime PRIVATE cxx_std_17) +target_link_libraries(startup_compute_builder_gate_runtime PRIVATE d3d12_xs_shim d3d12 dxgi) +set(startup_builder_gate_header "${CMAKE_CURRENT_BINARY_DIR}/startup_builder_gate_cs.h") +add_custom_command(OUTPUT "${startup_builder_gate_header}" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E main -Vn builder_gate_cs + -Fh "${startup_builder_gate_header}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_builder_gate.hlsl" + DEPENDS tests/startup_builder_gate.hlsl VERBATIM) +target_sources(startup_compute_builder_gate_runtime PRIVATE "${startup_builder_gate_header}") +target_include_directories(startup_compute_builder_gate_runtime PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_compute_builder_gate_runtime + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_builder_gate_runtime_check.py" + "$" "$") +endif() + +# Slot 67 request publication must keep its normal path with the gate enabled: slot 67 never +# carries the slot 62 builder tag. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + add_test(NAME startup_compute_builder_gate_request_warp + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_check.py" + "$") + set_tests_properties(startup_compute_builder_gate_request_warp PROPERTIES + ENVIRONMENT "X2W_COMPUTE_BUILDER_GATE=1" TIMEOUT 180) +endif() diff --git a/tests/startup_builder_gate.hlsl b/tests/startup_builder_gate.hlsl new file mode 100644 index 0000000000..f27724aa74 --- /dev/null +++ b/tests/startup_builder_gate.hlsl @@ -0,0 +1,2 @@ +[numthreads(1, 1, 1)] +void main() {} diff --git a/tests/startup_builder_module.cpp b/tests/startup_builder_module.cpp new file mode 100644 index 0000000000..c73c2abc79 --- /dev/null +++ b/tests/startup_builder_module.cpp @@ -0,0 +1,13 @@ +#include + +// A source-built module whose basename matches the console BVH builder. The gate resolves the +// caller of device slot 62; a call through this export must be tagged as a builder pipeline. +extern "C" __declspec(dllexport) HRESULT WINAPI CreateBuilderPipeline( + IUnknown* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID iid, void** out) +{ + if (!device || !desc || !out) return E_POINTER; + using Slot62 = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, UINT, + const void*, REFIID, void**); + const auto fn = reinterpret_cast((*reinterpret_cast(device))[62]); + return fn(device, desc, 0, nullptr, iid, out); +} diff --git a/tests/startup_compute_builder_gate_check.cpp b/tests/startup_compute_builder_gate_check.cpp new file mode 100644 index 0000000000..8c1b35ea07 --- /dev/null +++ b/tests/startup_compute_builder_gate_check.cpp @@ -0,0 +1,111 @@ +// Checks src/startup_stubs/compute_builder_gate.h without a device or a title module: when the +// opt-in console BVH builder gate allows a Dispatch, when it refuses a partial builder, and when a +// failed on-the-spot creation latches it off. Expectations are written out below, not computed with +// the header. +#include "startup_stubs/compute_builder_gate.h" + +#include +#include + +namespace { +using x2w_startup::BuilderGateDecision; +using x2w_startup::BuilderGateState; + +int failures, cases; + +void expect(bool condition, const char* label) +{ + ++cases; + if (condition) return; + ++failures; + std::printf("FAIL %s\n", label); +} + +void expect_decision(BuilderGateState& gate, bool builder_dispatch, BuilderGateDecision expected, const char* label) +{ + std::printf("case %s\n", label); + const BuilderGateDecision got = gate.decide(builder_dispatch); + ++cases; + if (got == expected) return; + ++failures; + std::printf("FAIL %s: expected '%s', got '%s'\n", label, x2w_startup::builder_gate_reason(expected), + x2w_startup::builder_gate_reason(got)); +} +} // namespace + +int main() +{ + using x2w_startup::is_compute_builder_module; + + expect(is_compute_builder_module(L"XboxBvhBuilder.dll"), "bare module name"); + expect(is_compute_builder_module(L"xboxbvHBuilder.DLL"), "case-insensitive module name"); + expect(is_compute_builder_module(L"C:\\Games\\XboxBvhBuilder.dll"), "backslash path"); + expect(is_compute_builder_module(L"C:/Games/XboxBvhBuilder.dll"), "forward-slash path"); + expect(!is_compute_builder_module(L"C:\\Games\\XboxBvhBuilderExtra.dll"), "extra suffix is not the builder"); + expect(!is_compute_builder_module(L"C:\\Games\\NotXboxBvhBuilder.dll"), "prefix is not the builder"); + expect(!is_compute_builder_module(L"C:\\Games\\XboxBvhBuilder.dll.bak"), "backup suffix is not the builder"); + expect(!is_compute_builder_module(L""), "empty path"); + expect(!is_compute_builder_module(L"C:\\Games\\"), "directory path"); + expect(!is_compute_builder_module(L"C:\\Games\\XboxBvhBuilder.dll\\"), "trailing slash has no basename"); + + char slots[BuilderGateState::max_pipelines + 1]{}; + + // Off by default: tracking is a no-op and the existing path is unchanged even with a missing set. + BuilderGateState disabled(false); + expect(disabled.note_pipeline(&slots[0], true, false), "disabled gate accepts a note"); + expect(disabled.tracked() == 0, "disabled gate tracks nothing"); + expect_decision(disabled, true, BuilderGateDecision::unchanged, "gate off leaves a builder Dispatch unchanged"); + expect_decision(disabled, false, BuilderGateDecision::unchanged, "gate off leaves a non-builder Dispatch unchanged"); + + // Every tracked builder pipeline present: the all-or-none set is allowed. + BuilderGateState gate(true); + expect(gate.note_pipeline(&slots[0], true, true), "track a real builder pipeline"); + expect(gate.note_pipeline(&slots[1], true, true), "track a second real builder pipeline"); + expect(gate.tracked() == 2 && gate.with_pso() == 2, "two builder pipelines with PSOs"); + expect_decision(gate, true, BuilderGateDecision::allow, "all builder pipelines have a PSO"); + expect_decision(gate, false, BuilderGateDecision::unchanged, "a non-builder Dispatch is unchanged"); + + // A non-builder pipeline never joins the tracked set and never blocks the builder. + expect(gate.note_pipeline(&slots[2], false, false), "ignore a non-builder pipeline"); + expect(gate.tracked() == 2 && gate.with_pso() == 2, "non-builder pipeline is not tracked"); + expect_decision(gate, true, BuilderGateDecision::allow, "non-builder pipeline leaves the builder allowed"); + + // One tracked builder pipeline without a PSO: refuse until the on-the-spot attempt fills it. + expect(gate.note_pipeline(&slots[3], true, false), "track a placeholder builder pipeline"); + expect(gate.tracked() == 3 && gate.with_pso() == 2, "one builder pipeline is missing its PSO"); + expect_decision(gate, true, BuilderGateDecision::refuse_missing, "one missing builder pipeline is refused"); + gate.note_pso(&slots[3]); + expect(gate.with_pso() == 3, "the created PSO joins the tracked set"); + expect_decision(gate, true, BuilderGateDecision::allow, "the completed builder set is allowed"); + + // A repeated creation updates the entry instead of duplicating it. + expect(gate.note_pipeline(&slots[3], true, true), "repeat an existing builder pipeline"); + expect(gate.tracked() == 3 && gate.with_pso() == 3, "the repeated pointer does not add an entry"); + + // One failed on-the-spot creation latches the builder off for the rest of the run. + BuilderGateState failed(true); + expect(failed.note_pipeline(&slots[0], true, true), "failed set: first pipeline"); + expect(failed.note_pipeline(&slots[1], true, false), "failed set: second pipeline is missing"); + expect_decision(failed, true, BuilderGateDecision::refuse_missing, "failed set starts refused"); + failed.note_failed("desktop pipeline creation failed"); + expect(failed.off(), "a failed creation latches the gate off"); + expect(std::strcmp(failed.first_reason(), "desktop pipeline creation failed") == 0, "first reason is kept"); + expect_decision(failed, true, BuilderGateDecision::refuse_off, "the off builder stays refused"); + expect_decision(failed, true, BuilderGateDecision::refuse_off, "the refusal is permanent"); + expect_decision(failed, false, BuilderGateDecision::unchanged, "the off builder leaves other Dispatches alone"); + + // An untrackable set is not silently allowed: filling the table latches the gate off. + BuilderGateState full(true); + for (unsigned i = 0; i < BuilderGateState::max_pipelines; ++i) + expect(full.note_pipeline(&slots[i], true, true), "fill the builder pipeline table"); + expect(full.tracked() == BuilderGateState::max_pipelines && full.with_pso() == BuilderGateState::max_pipelines, + "the full table is still all present"); + expect_decision(full, true, BuilderGateDecision::allow, "a full tracked set with every PSO is allowed"); + expect(!full.note_pipeline(&slots[BuilderGateState::max_pipelines], true, false), "an extra builder pipeline is refused"); + expect(full.off() && std::strcmp(full.first_reason(), "builder pipeline table is full") == 0, + "an untrackable builder set latches off"); + expect_decision(full, true, BuilderGateDecision::refuse_off, "the untrackable builder set stays refused"); + + std::printf("startup_compute_builder_gate: %d case(s), %d failure(s)\n", cases, failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_compute_builder_gate_runtime.cpp b/tests/startup_compute_builder_gate_runtime.cpp new file mode 100644 index 0000000000..91dfcd13ef --- /dev/null +++ b/tests/startup_compute_builder_gate_runtime.cpp @@ -0,0 +1,148 @@ +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "startup_builder_gate_cs.h" + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Microsoft::WRL::ComPtr; + +void check(HRESULT hr, const char* stage) +{ + if (SUCCEEDED(hr)) return; + std::fprintf(stderr, "%s failed: 0x%08lx\n", stage, static_cast(hr)); + std::exit(1); +} + +template +Method slot(IUnknown* object, unsigned index) +{ + return reinterpret_cast((*reinterpret_cast(object))[index]); +} + +using CreateBuilder = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, REFIID, void**); + +struct VirtualFreeDeleter { + void operator()(void* p) const noexcept { VirtualFree(p, 0, MEM_RELEASE); } +}; +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + const bool builder = std::strcmp(argv[2], "builder") == 0; + const bool completed = std::strcmp(argv[2], "completed") == 0; + if (!builder && !completed && std::strcmp(argv[2], "nonbuilder") != 0) return 2; + + SetEnvironmentVariableA("X2W_COMPUTE_BUILDER_GATE", "1"); + SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_D3D12_LIST_NOOP", "1"); + SetEnvironmentVariableA("X2W_D3D12_RENDER", "1"); + + ComPtr factory; + ComPtr warp; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "DXGI factory"); + check(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp)), "WARP adapter"); + + ComPtr guest; + const std::uint64_t create_params[8]{}; + check(D3D12XboxCreateDevice(warp.Get(), create_params, IID_PPV_ARGS(&guest)), "guest device"); + + // A console container: slot 62 accepts it as a placeholder, and the builder gate must refuse to + // create a desktop PSO from it. The bytes are only read for the refusal, never submitted. + static const unsigned char console_code[64] = {'D', 'X', 'B', 'C'}; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.CS = {console_code, sizeof(console_code)}; + + ComPtr root; + if (completed) { + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + ComPtr root_blob; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &root_blob, nullptr), + "serialize empty root"); + check(guest->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), + IID_PPV_ARGS(&root)), "empty root"); + desc.pRootSignature = root.Get(); + desc.CS = {builder_gate_cs, sizeof(builder_gate_cs)}; + } + + using Slot62 = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, UINT, + const void*, REFIID, void**); + ComPtr pipeline; + if (builder || completed) { + const std::wstring path(argv[1], argv[1] + std::strlen(argv[1])); + HMODULE module = LoadLibraryW(path.c_str()); + if (!module) return 3; + const auto create = reinterpret_cast(GetProcAddress(module, "CreateBuilderPipeline")); + if (!create) return 4; + check(create(guest.Get(), &desc, IID_PPV_ARGS(&pipeline)), "builder pipeline"); + ComPtr second; + check(create(guest.Get(), &desc, IID_PPV_ARGS(&second)), "second builder pipeline"); + } else { + check(slot(guest.Get(), 62)(guest.Get(), &desc, 0, nullptr, IID_PPV_ARGS(&pipeline)), + "non-builder pipeline"); + } + + ComPtr allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + const UINT list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + using CreateList = HRESULT(WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); + ComPtr list; + check(slot(guest.Get(), 73)(guest.Get(), list_desc, allocator.Get(), nullptr, IID_PPV_ARGS(&list)), + "list"); + using Reset = HRESULT(WINAPI*)(IUnknown*, IUnknown*, void*, void*); + check(slot(list.Get(), 139)(list.Get(), allocator.Get(), nullptr, nullptr), "reset"); + + using SetPipeline = void(WINAPI*)(IUnknown*, IUnknown*); + using Dispatch = void(WINAPI*)(IUnknown*, UINT, UINT, UINT); + using Root = void(WINAPI*)(IUnknown*, IUnknown*); + if (completed) slot(list.Get(), 33)(list.Get(), root.Get()); + slot(list.Get(), 25)(list.Get(), pipeline.Get()); + slot(list.Get(), 14)(list.Get(), 1, 1, 1); + + ComPtr argument_buffer; + std::unique_ptr backing( + VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (completed) { + if (!backing) return 5; + auto* address = static_cast(backing.get()) + 4; + const D3D12_DISPATCH_ARGUMENTS arguments{1, 1, 1}; + std::memcpy(address, &arguments, sizeof(arguments)); + 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; + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + using Place = HRESULT(WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, + void**); + check(slot(guest.Get(), 133)(guest.Get(), address, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&argument_buffer)), + "argument placed buffer"); + } + + D3D12_INDIRECT_ARGUMENT_DESC argument{}; + argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + D3D12_COMMAND_SIGNATURE_DESC signature_desc{}; + signature_desc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS); + signature_desc.NumArgumentDescs = 1; + signature_desc.pArgumentDescs = &argument; + using CreateSignature = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMMAND_SIGNATURE_DESC*, IUnknown*, REFIID, + void**); + ComPtr signature; + check(slot(guest.Get(), 41)(guest.Get(), &signature_desc, nullptr, IID_PPV_ARGS(&signature)), + "signature"); + + using Execute = void(WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); + slot(list.Get(), 61)(list.Get(), signature.Get(), 1, argument_buffer.Get(), 0, nullptr, 0); + std::printf("%s done\n", argv[2]); + return 0; +} diff --git a/tests/startup_compute_builder_gate_runtime_check.py b/tests/startup_compute_builder_gate_runtime_check.py new file mode 100644 index 0000000000..8911559859 --- /dev/null +++ b/tests/startup_compute_builder_gate_runtime_check.py @@ -0,0 +1,34 @@ +"""Public slot 62 and indirect paths with the opt-in builder gate and a source-built module.""" +from pathlib import Path +import os +import subprocess +import sys + + +def run(executable, module, mode): + env = dict(os.environ, X2W_COMPUTE_BUILDER_GATE="1", X2W_D3D12_PERMISSIVE="1", + X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1") + result = subprocess.run([str(Path(executable).resolve()), str(Path(module).resolve()), mode], + capture_output=True, text=True, env=env) + assert result.returncode == 0, (mode, result.returncode, result.stdout, result.stderr) + return result.stderr + + +def main(executable, module): + builder = run(executable, module, "builder") + assert "compute builder gate" in builder, builder + assert "Dispatch refused" in builder, builder + assert "ExecuteIndirect refused" in builder, builder + + nonbuilder = run(executable, module, "nonbuilder") + assert "compute builder gate" not in nonbuilder, nonbuilder + + completed = run(executable, module, "completed") + assert "all have a desktop PSO" in completed, completed + assert "requires a desktop compute pipeline and root" not in completed, completed + assert "ExecuteIndirect refused" not in completed, completed + print("builder gate: incomplete set refused; completed set dispatch reaches the list; non-builder untouched") + + +if __name__ == "__main__": + main(sys.argv[1], sys.argv[2])