diff --git a/CMakePresets.json b/CMakePresets.json index 8fff29df2..3803e6199 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -48,7 +48,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_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_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|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)$" + "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_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_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_mesh_argument_provenance_warp|startup_shader_cache_key|startup_present_readback|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)$" } } }, diff --git a/docs/experiments/mesh-argument-provenance.md b/docs/experiments/mesh-argument-provenance.md new file mode 100644 index 000000000..650a82024 --- /dev/null +++ b/docs/experiments/mesh-argument-provenance.md @@ -0,0 +1,155 @@ +# GPU-written Mesh arguments and descriptor history + +Refs [#3310](https://github.com/R0Y00/Xbox2Windows/issues/3310). +This adds a source-built reproducer and an opt-in descriptor diagnostic. It +does not establish the issue's matched integration acceptance or repair the +zero launch count observed there. + +## What the fixture measures + +`startup_mesh_argument_provenance_hardware` uses the existing +`startup_indirect_draw_indexed` executable in `mesh-provenance` mode. All shader +and buffer inputs come from repository source. No external capture, shader +cache, game content or fitted parameters are required. + +The fixture follows this chain: + +1. Create a raw buffer SRV in a CPU-only guest descriptor heap. Copy it to a + shader-visible heap, overwrite the source SRV, then copy the updated view. + The guest token and desktop shadow record have different identities. +2. A source-built Compute dispatch writes the scalar input: `2` at byte 16 + and `0` at byte 32. Copy those bytes to readback before the updater. After + fence 1 completes, verify that this GPU write supplied the nonzero input. +3. A second Compute dispatch reads `launch.Load(0)` through the copied SRV + and writes `(X,1,1)` into the argument buffer at byte 4. Copy the argument + buffer to a separate readback allocation and complete fence 1. +4. In a separate submission on the same DIRECT queue, copy that buffer again + immediately before the guest command-list slot 61 `ExecuteIndirect` call. + Complete fence 2 before mapping the second snapshot. Report the exact + consumed 12-byte interval, backing resource and byte offset. +5. Read back the scene-color target after fence 3. The positive case checks + every pixel of the 4 by 2 RGBA8 target: left red, right green. No compositor + participates. Check the argument buffer's leading, trailing and neighboring + record guards, device-removal status and debug-layer errors too. + +The positive oracle requires the same resource **and** offset, identical +12-byte records with X greater than zero, intact guards and all eight expected +pixels. Each negative control must fail that same oracle while satisfying its +own expected record and pixel results: + +| Case | Post-write record at byte 4 | Pre-consume record | Changed pixels | +|---|---|---|---| +| `positive` | `(2,1,1)` | byte 4: `(2,1,1)` | 8/8 | +| `missing-copy` | `(0,1,1)` | byte 4: `(0,1,1)` | 0/8 | +| `stale-copy` | `(0,1,1)` | byte 4: `(0,1,1)` | 0/8 | +| `wrong-srv-offset` | `(0,1,1)` | byte 4: `(0,1,1)` | 0/8 | +| `wrong-argument-offset` | `(2,1,1)` | byte 20: `(0,1,1)` | 0/8 | + +The missing-copy destination is explicitly initialized with a null SRV. The +stale-copy case copies the original view at byte 32, then overwrites the source +to byte 16 without copying again. The wrong-SRV case copies a view still +pointing at byte 32. The wrong-argument case consumes a valid zero record in +the same resource, so a same-resource-only comparison would miss the error. +The Python driver also repeats the positive case with history tracing disabled +and requires the same argument and pixel results without history lines. + +## Runtime diagnostic + +Set `X2W_D3D12_DESCRIPTOR_HISTORY=1` **before process startup**. The setting is +cached. Output follows the usual trap logger, stderr unless `X2W_TRAP_LOG` is +set. It emits `x2w-descriptor-history` lines for intercepted view creation into +tracked shadow slots and intercepted descriptor copies: + +| Field | Meaning | +|---|---| +| `seq` | CPU shadow-publication order, serialized by `note_lock`; not GPU execution order | +| `op` | `create` or `copy`; a create with a different `old`/`new` ID is an overwrite | +| `guest`, `desktop`, `source` | Destination guest address, destination desktop handle, and source guest address for a copy | +| `old`, `new` | Shadow IDs before and after publication; 0 means unknown, otherwise the view-record index plus 1 | +| `slot` | Recorded device view-creation slot, for example 18 for SRV | +| `resource`, `backing` | Recorded guest resource identity and its unwrapped desktop backing resource | +| `first`, `stride` | Buffer SRV `FirstElement` and `StructureByteStride`; raw SRV byte offset is `first * 4` | +| `materialized` | Whether the recorded view was materialized on the desktop | +| `guest_bytes`, `guest_read`, `guest_before` | Requested token sample size, successful complete read flag, and up to eight hexadecimal DWORDs **before this operation writes the guest token** | + +SRV tokens occupy 32 bytes. Sampler tokens use the shorter sampler stride; the +remaining printed words are zero padding. Only a sample with `guest_read=1` +can be interpreted. Guest token word 1 is a zero-based view-record index, +whereas `old`/`new` use one-based IDs. Native desktop descriptor bytes are +opaque and are not read as guest tokens. + +The diagnostic records at most 8,192 events per process, then emits one +`truncated limit=8192` line. A truncated run has incomplete history. Arbitrary +guest CPU stores or `memcpy` operations are not intercepted. View creations +without a tracked desktop shadow slot and view-record allocation failures do +not produce creation events. The sequence describes shadow updates; guest +token memory writes occur afterward and concurrently reused slots still +require the caller's synchronization. + +This switch adds no GPU commands, barriers, readbacks or waits. The source-built +fixture supplies its own fenced GPU snapshots. When the switch is unset, it +does not sample guest memory or add the per-descriptor history loop. The +diagnostic changes neither descriptor-copy policy nor the rendering path. + +## Reproduce + +Use the ordinary Windows build prerequisites in +[CONTRIBUTING.md](../../CONTRIBUTING.md#build-and-test), including DXC and Python. +Mesh requires a capable adapter/runtime. On an older Windows installation, +configure the existing `OFFSCREEN_AGILITY_620_DIR` option with a local directory +containing the public Agility 620 `D3D12Core.dll` and `d3d12SDKLayers.dll`. +Neither DLL is part of this contribution. + +```powershell +. .\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target startup_indirect_draw_indexed startup_compute_binding_trace startup_view_alloc startup_view_census +ctest --preset dev --no-tests=error -j 1 -V -R '^startup_(mesh_argument_provenance_(warp|hardware)|indirect_mesh_(warp|hardware)|view_alloc_.*|view_census_.*|compute_binding_trace_warp)$' + +cmake --preset release +cmake --build --preset release --target startup_indirect_draw_indexed startup_compute_binding_trace startup_view_alloc startup_view_census +ctest --preset release --no-tests=error -j 1 -V -R '^startup_(mesh_argument_provenance_(warp|hardware)|indirect_mesh_(warp|hardware)|view_alloc_.*|view_census_.*|compute_binding_trace_warp)$' +``` + +To inspect the unfiltered diagnostic for one case: + +```powershell +$env:X2W_D3D12_DESCRIPTOR_HISTORY = '1' +$env:X2W_MESH_PROVENANCE_CASE = 'positive' +.\out\build\dev\startup_indirect_draw_indexed.exe hardware mesh-provenance +``` + +`startup_mesh_argument_provenance_warp` is included in the PR smoke-test preset. +Capability skips return 77 and must be reported separately from passes. + +## Local result and remaining integration work + +Tested on 28 November 2026, Windows 10 Pro build 19045, NVIDIA GeForce RTX +4070 Ti SUPER, driver `32.0.15.7270`, MSVC `19.43.34810`, DXC `1.9.2609`, +Agility SDK 620, D3D12 debug layer enabled. Build: this change on base +`32dc3d7c3cdc4be79afdad4cc04709e76d99a795`. + +Debug and Release each ran the 23 selected tests: 21 passed, zero failed, +and two capability skips (`startup_indirect_mesh_warp` and +`startup_mesh_argument_provenance_warp`, Mesh shaders unavailable on local +WARP). The hardware provenance test runs six processes: the positive case, +four negative controls and the positive case without tracing. All had the +expected records, pixel readback and descriptor history, with no debug-layer +ERROR/CORRUPTION messages or device removal. + +The producers use desktop source-built HLSL on a native command list. View +creation/copy and the indirect Mesh consumer use the guest wrappers; queue +execution and fences are native. This does not exercise a translated gfx1013 +producer, guest queue preprocessing, XMem argument refresh, or the real +integration's root/attachment state. + +Issue #3310 remains open until a matched integration run identifies the actual +scalar-input write and descriptor history, reads identical nonzero records at +the same resource and offset after production and before consumption, and +observes a real Mesh submission changing scene color before composition. The +issue's reported 48 zero records were not reproduced by this fixture. No +matched integration configuration or capture is included in this change. +The native integration work in +[#3091](https://github.com/R0Y00/Xbox2Windows/pull/3091) and +[#3094](https://github.com/R0Y00/Xbox2Windows/pull/3094) was still open when this +result was recorded; it has not been substituted for a test of `main`. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 4b1a3e002..936f84827 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1652,6 +1652,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | | `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | | `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | +| `X2W_D3D12_DESCRIPTOR_HISTORY=1` | diagnostic only: logs bounded view creation/overwrite and descriptor-copy history with guest token bytes, shadow IDs and desktop backing identities. CPU publication order is separate from GPU execution ([fixture, controls and limits](experiments/mesh-argument-provenance.md)) | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_D3D12_TABLE_ALIAS=1` | opt-in, render mode: a translated draw's table buffer view whose whole range lies in a slot 133 placed buffer that aliases title memory binds that alias instead of a per-draw frame copy, so the GPU reads the bytes at execution and the view is not cut at 16 MiB (`startup_table_alias_*`). Unset, every table buffer view is copied as before. See [Copies of title memory within a frame](#copies-of-title-memory-within-a-frame) | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 05d0259d7..6f467b328 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -427,6 +427,51 @@ void drop_unrecorded_view(const ViewRecord& record, bool materialized, const cha container, record.slot); } +// Opt-in, bounded descriptor provenance. Called with note_lock held: sequence is +// the order in which shadow updates are published, not GPU execution order. +// Guest bytes are sampled BEFORE this operation publishes its token/copy. +bool descriptor_history_enabled() +{ + static const bool enabled = x2w_local::env_on("X2W_D3D12_DESCRIPTOR_HISTORY"); + return enabled; +} +void trace_descriptor_history(const char* operation, u64 title, u64 desktop, u64 source, + std::uint32_t previous, std::uint32_t next, UINT token_bytes) +{ + if (!descriptor_history_enabled()) return; + static u64 sequence; + const u64 event = ++sequence; + if (event > 8192) { + if (event == 8193) log("x2w-descriptor-history truncated limit=8192"); + return; + } + const DWORD saved_error = GetLastError(); + std::uint32_t guest[8]{}; + const UINT guest_bytes = (std::min)(token_bytes, UINT{sizeof(guest)}); + SIZE_T copied = 0; + const bool readable = guest_bytes && title != desktop && ReadProcessMemory(GetCurrentProcess(), + reinterpret_cast(title), guest, guest_bytes, &copied) && copied == guest_bytes; + const ViewRecord* view = next && next - 1 < view_records().size() ? &view_records()[next - 1] : nullptr; + u64 first = 0; + UINT stride = 0; + if (view && view->slot == 18 && view->desc_bytes >= sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) { + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + std::memcpy(&srv, view->desc, sizeof(srv)); + if (srv.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { + first = srv.Buffer.FirstElement; + stride = srv.Buffer.StructureByteStride; + } + } + log("x2w-descriptor-history seq=%llu op=%s guest=%llx desktop=%llx source=%llx old=%u new=%u " + "slot=%u resource=%llx backing=%llx first=%llu stride=%u materialized=%u guest_bytes=%u guest_read=%u " + "guest_before=%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x", + event, operation, title, desktop, source, previous, next, view ? view->slot : 0, + view ? view->resource : 0, view ? unwrap(view->resource) : 0, first, stride, + view && view_materialized()[next - 1] ? 1 : 0, guest_bytes, readable ? 1 : 0, + guest[0], guest[1], guest[2], guest[3], guest[4], guest[5], guest[6], guest[7]); + SetLastError(saved_error); +} + // A view is created: remembered by id; the id is also written into title-owned descriptor memory so // that copies the title makes there itself can be followed. void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_t desc_bytes, u64 dest_title, u64 dest_desktop, @@ -491,6 +536,8 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ } if (std::uint32_t* slot_ptr = shadow_slot(dest_desktop)) { const std::uint32_t prev = *slot_ptr; + trace_descriptor_history("create", dest_title, dest_desktop, 0, prev, record.id + 1, + slot == 22 ? x2w_startup::title_sampler_stride : 32u); *slot_ptr = record.id + 1; // The same view written to the same slot again keeps its id and changes no reference count. A different view // takes over the slot: the new record adds its refs, the previous materialized record drops its own. @@ -515,11 +562,21 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ } void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, UINT count, UINT increment) { + const bool history = descriptor_history_enabled(); + const UINT dest_stride = history ? title_descriptor_stride(dest_title, increment) : 0; + const UINT src_stride = history ? title_descriptor_stride(src_title, increment) : 0; AcquireSRWLockExclusive(¬e_lock); descriptors_copied += count; std::uint32_t dest_room = 0, src_room = 0; std::uint32_t* to = shadow_slot(dest_desktop, &dest_room); const std::uint32_t* from = shadow_slot(src_desktop, &src_room); + if (history) + for (UINT i = 0; i < count; ++i) { + const auto previous = to && i < dest_room ? to[i] : 0; + const auto next = to && count <= dest_room ? (from && count <= src_room ? from[i] : 0) : previous; + trace_descriptor_history("copy", dest_title + u64{i} * dest_stride, dest_desktop + u64{i} * increment, + src_title + u64{i} * src_stride, previous, next, dest_stride); + } if (to && count <= dest_room) { if (from && count <= src_room) { // Every copied-in view is now named by one more tracked slot; every view the destination named before is diff --git a/tests/cmake/mesh_argument_provenance.cmake b/tests/cmake/mesh_argument_provenance.cmake new file mode 100644 index 000000000..1eedb0aff --- /dev/null +++ b/tests/cmake/mesh_argument_provenance.cmake @@ -0,0 +1,10 @@ +# Reuse the existing source-built mesh executable and its generated DXIL. +if(EXISTS "${INTAKE_PYTHON}") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_mesh_argument_provenance_${adapter} + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh_argument_provenance_check.py" + "$" ${adapter}) + set_tests_properties(startup_mesh_argument_provenance_${adapter} PROPERTIES + TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 563e9ab30..b021dc1a1 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1763,6 +1763,8 @@ bool fixed_mesh_create_contract(ID3D12Device* guest) #include "startup_indirect_mesh_lease.inl" } // namespace +#include "startup_mesh_argument_provenance.inl" + int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; @@ -1807,7 +1809,8 @@ int main(int argc, char** argv) try const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if ((translated && !translated_indexed) || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; else if (argc == 3 && std::strcmp(argv[2], "rect") == 0) kind = DrawKind::rect; - else if (lease_arguments || console_mesh || desktop_as || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) + else if (lease_arguments || console_mesh || desktop_as || (argc == 3 && + (std::strcmp(argv[2], "mesh") == 0 || std::strcmp(argv[2], "mesh-provenance") == 0))) kind = DrawKind::mesh; else if (rect) kind = DrawKind::indexed_rect; else if (argc != 2 && !count_control && !translated_indexed && !lease_writer) return 2; @@ -2440,6 +2443,9 @@ int main(int argc, char** argv) try ComPtr signature; check(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)), "create guest draw signature"); + if (argc == 3 && std::strcmp(argv[2], "mesh-provenance") == 0) + return check_mesh_argument_provenance(device.Get(), guest.Get(), graphics.Get(), pso.Get(), signature.Get()) ? 0 : 1; + if (lease_arguments) { if (!lease_fixture) return 2; return check_mesh_indirect_xmem(device.Get(), guest.Get(), lease_xmem, info.Get(), log_path, diff --git a/tests/startup_mesh_argument_provenance.inl b/tests/startup_mesh_argument_provenance.inl new file mode 100644 index 000000000..c735b1509 --- /dev/null +++ b/tests/startup_mesh_argument_provenance.inl @@ -0,0 +1,266 @@ +// Source-built descriptor -> compute writer -> indirect Mesh chain (Refs #3310). +// Included in startup_indirect_draw_indexed.cpp to reuse its real guest wrapper, +// placed-resource helper, Mesh shaders and complete pixel oracle. +bool check_mesh_argument_provenance(ID3D12Device* device, ID3D12Device* guest, + ID3D12RootSignature* graphics_root, IUnknown* graphics, ID3D12CommandSignature* signature) +{ + char setting[64]{}; + GetEnvironmentVariableA("X2W_MESH_PROVENANCE_CASE", setting, sizeof(setting)); + const std::string scenario = setting; + const bool missing = scenario == "missing-copy"; + const bool stale = scenario == "stale-copy"; + const bool wrong_srv = scenario == "wrong-srv-offset"; + const bool wrong_argument = scenario == "wrong-argument-offset"; + if (!scenario.empty() && scenario != "positive" && !missing && !stale && !wrong_srv && !wrong_argument) + return false; + const char* label = scenario.empty() ? "positive" : scenario.c_str(); + constexpr UINT64 input_offset = 16; + constexpr UINT64 written_offset = 4; + const UINT64 consumed_offset = wrong_argument ? 20 : written_offset; + const UINT expected_x = missing || stale || wrong_srv ? 0 : 2; + const UINT consumed_x = wrong_argument ? 0 : expected_x; + const Words seed{0xa5a5a5a5, 0, 1, 1, 0x5a5a5a5a, 0, 1, 1, 0x12345678}; + PlacedBuffer arguments(device, guest, sizeof(seed), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + PlacedBuffer input(device, guest, 64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto upload = make_buffer(device, sizeof(seed), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void* memory = nullptr; + const D3D12_RANGE none{0, 0}; + check(upload->Map(0, &none, &memory), "map provenance seed"); + std::memcpy(memory, seed.data(), sizeof(seed)); + upload->Unmap(0, &none); + + constexpr char producer[] = R"( +ByteAddressBuffer launch : register(t0); +RWByteAddressBuffer data : register(u0); +[numthreads(1,1,1)] void seed_input() { data.Store(16, 2); data.Store(32, 0); } +[numthreads(1,1,1)] void update_args() { data.Store3(4, uint3(launch.Load(0), 1, 1)); } +)"; + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[0].DescriptorTable = {1, &range}; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + const auto writer_root = create_root(device, {2, parameters}); + const auto pipeline = [&](const char* entry) { + ComPtr code, errors; + const HRESULT hr = D3DCompile(producer, sizeof(producer) - 1, nullptr, nullptr, nullptr, + entry, "cs_5_1", 0, 0, &code, &errors); + if (FAILED(hr) && errors) std::fprintf(stderr, "%s\n", static_cast(errors->GetBufferPointer())); + check(hr, entry); + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = writer_root.Get(); + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + ComPtr result; + check(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&result)), entry); + return result; + }; + const auto seed_pipeline = pipeline("seed_input"), update_pipeline = pipeline("update_args"); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ComPtr heap, source_heap; + check(guest->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "create provenance descriptor heap"); + const D3D12_DESCRIPTOR_HEAP_DESC source_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}; + check(guest->CreateDescriptorHeap(&source_desc, IID_PPV_ARGS(&source_heap)), "create CPU copy-source heap"); + const auto native_heap = native_object(device, guest, heap.Get()); + using Handle = UINT64 (WINAPI*)(IUnknown*, void*); + const UINT64 guest_cpu = slot(source_heap.Get(), 9)(source_heap.Get(), nullptr); + const UINT64 bound_cpu = slot(heap.Get(), 9)(heap.Get(), nullptr); + const UINT64 desktop_cpu = native_heap->GetCPUDescriptorHandleForHeapStart().ptr; + using View = void (WINAPI*)(IUnknown*, IUnknown*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, UINT64, UINT64); + using Copy = void (WINAPI*)(IUnknown*, UINT, UINT64, UINT64, D3D12_DESCRIPTOR_HEAP_TYPE); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = 1; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + const auto create_srv = [&](UINT index, UINT64 byte_offset, bool null_resource = false) { + srv.Buffer.FirstElement = byte_offset / 4; + slot(guest, 18)(guest, null_resource ? nullptr : input.wrapped.Get(), &srv, + index ? bound_cpu : guest_cpu, 0); + }; + // A known null destination makes the missing-copy control deterministic. + create_srv(1, 0, true); + create_srv(0, input_offset + 16); + if (!missing) slot(guest, 24)(guest, 1, bound_cpu, guest_cpu, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + create_srv(0, wrong_srv ? input_offset + 16 : input_offset); // overwrite the source + if (!missing && !stale) slot(guest, 24)(guest, 1, bound_cpu, guest_cpu, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + std::uint32_t tokens[2][8]{}; + std::memcpy(tokens[0], reinterpret_cast(guest_cpu), 32); + std::memcpy(tokens[1], reinterpret_cast(bound_cpu), 32); + std::printf("provenance descriptor case=%s guest=%llx desktop=%llx source=%llx " + "input=%p input_offset=%llu token_source=%08x,%u token_bound=%08x,%u\n", label, + bound_cpu, desktop_cpu, guest_cpu, + static_cast(input.native.Get()), wrong_srv || stale ? input_offset + 16 : missing ? 0 : input_offset, + tokens[0][0], tokens[0][1], tokens[1][0], tokens[1][1]); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr queue; + ComPtr completion; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "create provenance DIRECT queue"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&completion)), "create provenance fence"); + ComPtr snapshots[2]; + const auto input_snapshot = make_buffer(device, 64, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + Words observed[2]{}; + Words expected = seed; + expected[1] = expected_x; + const auto read_record = [&](UINT i) { + const D3D12_RANGE read{0, sizeof(seed)}; + check(snapshots[i]->Map(0, &read, &memory), "map provenance argument snapshot"); + std::memcpy(observed[i].data(), memory, sizeof(seed)); + snapshots[i]->Unmap(0, &none); + const UINT index = static_cast((i ? consumed_offset : written_offset) / 4); + std::printf("provenance record phase=%s resource=%p offset=%llu tuple=%u,%u,%u guards=%s\n", + i ? "pre-consume" : "post-write", static_cast(arguments.native.Get()), + i ? consumed_offset : written_offset, observed[i][index], observed[i][index + 1], observed[i][index + 2], + observed[i] == expected ? "intact" : "BAD"); + return observed[i] == expected; + }; + const auto wait = [&](UINT64 value, const char* phase) { + check(queue->Signal(completion.Get(), value), "signal provenance fence"); + const auto deadline = GetTickCount64() + 10000; + while (completion->GetCompletedValue() < value && GetTickCount64() < deadline) Sleep(1); + check(device->GetDeviceRemovedReason(), "provenance device completion"); + check(completion->GetCompletedValue() >= value ? S_OK : E_FAIL, "wait provenance fence"); + std::printf("provenance fence phase=%s queue=%p fence=%p value=%llu completed=%llu\n", + phase, static_cast(queue.Get()), static_cast(completion.Get()), value, + completion->GetCompletedValue()); + }; + { + ComputeCommands commands(device, queue.Get(), nullptr); + auto* list = commands.list.Get(); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(arguments.native.Get(), 0, upload.Get(), 0, sizeof(seed)); + transition(list, input.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->SetComputeRootSignature(writer_root.Get()); + list->SetPipelineState(seed_pipeline.Get()); + list->SetComputeRootUnorderedAccessView(1, input.native->GetGPUVirtualAddress()); + std::printf("provenance input-write queue=%p resource=%p offset=%llu value=2 dispatch=1,1,1\n", + static_cast(queue.Get()), static_cast(input.native.Get()), input_offset); + list->Dispatch(1, 1, 1); + transition(list, input.native.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(input_snapshot.Get(), 0, input.native.Get(), 0, 64); + transition(list, input.native.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[]{native_heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + auto bound = native_heap->GetGPUDescriptorHandleForHeapStart(); + list->SetComputeRootDescriptorTable(0, bound); + list->SetComputeRootUnorderedAccessView(1, arguments.native->GetGPUVirtualAddress()); + list->SetPipelineState(update_pipeline.Get()); + std::printf("provenance producer queue=%p resource=%p offset=%llu bytes=12 dispatch=1,1,1\n", + static_cast(queue.Get()), static_cast(arguments.native.Get()), written_offset); + list->Dispatch(1, 1, 1); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + snapshots[0] = make_buffer(device, sizeof(seed), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(snapshots[0].Get(), 0, arguments.native.Get(), 0, sizeof(seed)); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + transition(list, input.native.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + check(list->Close(), "close provenance writer"); + ID3D12CommandList* lists[]{list}; + queue->ExecuteCommandLists(1, lists); + wait(1, "post-write"); + } + const D3D12_RANGE input_range{input_offset, input_offset + 20}; + check(input_snapshot->Map(0, &input_range, &memory), "map provenance scalar input"); + UINT launch = 0, adjacent = 0; + std::memcpy(&launch, static_cast(memory) + input_offset, sizeof(launch)); + std::memcpy(&adjacent, static_cast(memory) + input_offset + 16, sizeof(adjacent)); + input_snapshot->Unmap(0, &none); + std::printf("provenance input-record resource=%p offset=%llu value=%u adjacent_offset=%llu adjacent_value=%u\n", + static_cast(input.native.Get()), input_offset, launch, input_offset + 16, adjacent); + if (launch != 2 || adjacent != 0 || !read_record(0)) return false; + // Separate consumer submission. The second copy is immediately before the + // guest ExecuteIndirect and uses the exact resource/offset being consumed. + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE clear_value{format, {0, 0, 0, 1}}; + const auto target = resource(device, target_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &clear_value); + ComPtr rtv_heap; + const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + check(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap)), "create provenance RTV heap"); + const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + guest->CreateRenderTargetView(target.Get(), nullptr, rtv); + ComPtr allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "create provenance allocator"); + const auto wrapped = begin_guest_list(guest, allocator.Get()); + const auto native_list = native_object(device, guest, wrapped.Get()); + auto* list = native_list.Get(); + using Bind = void (WINAPI*)(IUnknown*, IUnknown*); + using Targets = void (WINAPI*)(IUnknown*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, const D3D12_CPU_DESCRIPTOR_HANDLE*); + using Clear = void (WINAPI*)(IUnknown*, SIZE_T, const float*, UINT, const D3D12_RECT*); + const float clear[]{0, 0, 0, 1}; + slot(wrapped.Get(), 52)(wrapped.Get(), rtv.ptr, clear, 0, nullptr); + slot(wrapped.Get(), 50)(wrapped.Get(), 1, &rtv, FALSE, nullptr); + slot(wrapped.Get(), 34)(wrapped.Get(), graphics_root); + slot(wrapped.Get(), 25)(wrapped.Get(), graphics); + const D3D12_VIEWPORT viewport{0, 0, width, height, 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + slot(wrapped.Get(), 21)(wrapped.Get(), 1, &viewport); + slot(wrapped.Get(), 22)(wrapped.Get(), 1, &scissor); + // Snapshot all guard words too; report only the consumed 12-byte interval. + snapshots[1] = make_buffer(device, sizeof(seed), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(snapshots[1].Get(), 0, arguments.native.Get(), 0, sizeof(seed)); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + std::printf("provenance consumer queue=%p resource=%p offset=%llu bytes=12\n", + static_cast(queue.Get()), static_cast(arguments.native.Get()), consumed_offset); + using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); + slot(wrapped.Get(), 61)(wrapped.Get(), signature, 1, arguments.wrapped.Get(), consumed_offset, nullptr, 0); + check(slot(wrapped.Get(), 9)(wrapped.Get()), "close provenance consumer"); + ID3D12CommandList* lists[]{list}; + queue->ExecuteCommandLists(1, lists); + wait(2, "pre-consume-copy-and-mesh"); + if (!read_record(1) || observed[0] != observed[1]) return false; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + device->GetCopyableFootprints(&target_desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + const auto pixels = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands capture(device, queue.Get(), nullptr); + transition(capture.list.Get(), target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION source{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + D3D12_TEXTURE_COPY_LOCATION destination{pixels.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + destination.PlacedFootprint = footprint; + capture.list->CopyTextureRegion(&destination, 0, 0, 0, &source, nullptr); + check(capture.list->Close(), "close provenance pixel capture"); + ID3D12CommandList* captures[]{capture.list.Get()}; + queue->ExecuteCommandLists(1, captures); + wait(3, "scene-color-readback"); + const D3D12_RANGE pixel_range{0, static_cast(bytes)}; + check(pixels->Map(0, &pixel_range, &memory), "map provenance pixels"); + UINT changed = 0; + bool correct = true; + for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) { + UINT actual = 0; + std::memcpy(&actual, static_cast(memory) + footprint.Offset + y * footprint.Footprint.RowPitch + 4 * x, 4); + const UINT wanted = consumed_x ? (x < width / 2 ? red : green) : black; + changed += actual != black; + if (actual != wanted) { + std::fprintf(stderr, "provenance pixel %u,%u: %08x != %08x\n", x, y, actual, wanted); + correct = false; + } + } + pixels->Unmap(0, &none); + std::printf("provenance result case=%s changed=%u total=%u writer_x=%u consumer_x=%u\n", + label, changed, width * height, expected_x, consumed_x); + ComPtr messages; + if (SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&messages)))) { + for (UINT64 i = 0; i < messages->GetNumStoredMessagesAllowedByRetrievalFilter(); ++i) { + SIZE_T size = 0; + check(messages->GetMessage(i, nullptr, &size), "size provenance debug message"); + std::vector storage(size); + auto* message = reinterpret_cast(storage.data()); + check(messages->GetMessage(i, message, &size), "read provenance debug message"); + if (message->Severity == D3D12_MESSAGE_SEVERITY_ERROR || + message->Severity == D3D12_MESSAGE_SEVERITY_CORRUPTION) { + std::fprintf(stderr, "provenance debug error: %s\n", message->pDescription); + correct = false; + } + } + } + return correct; +} diff --git a/tests/startup_mesh_argument_provenance_check.py b/tests/startup_mesh_argument_provenance_check.py new file mode 100644 index 000000000..b9dc03bef --- /dev/null +++ b/tests/startup_mesh_argument_provenance_check.py @@ -0,0 +1,134 @@ +"""Observe the source-built SRV -> GPU writer -> indirect Mesh chain. + +The positive oracle requires matching resource AND byte interval, X > 0 and +the expected scene-color pixels. Controls must fail that same positive oracle. +""" +from pathlib import Path +import os +import subprocess +import sys + + +CASES = ("positive", "missing-copy", "stale-copy", "wrong-srv-offset", "wrong-argument-offset") + + +def fields(line): + return dict(part.split("=", 1) for part in line.split() if "=" in part) + + +def observations(stdout, prefix): + return [fields(line) for line in stdout.splitlines() if line.startswith(prefix)] + + +def positive_oracle(records, result): + before, after = records + return (before["resource"].lower() == after["resource"].lower() + and before["offset"] == after["offset"] + and before["tuple"] == after["tuple"] + and int(before["tuple"].split(",")[0]) > 0 + and before["guards"] == after["guards"] == "intact" + and int(result["changed"]) == int(result["total"]) == 8) + + +def check_history(stdout, stderr, scenario): + descriptor, = observations(stdout, "provenance descriptor ") + history = observations(stderr, "x2w-descriptor-history seq=") + assert history, "missing descriptor history" + sequences = [int(event["seq"]) for event in history] + assert sequences == list(range(1, len(history) + 1)), sequences + destination = descriptor["guest"] + source = descriptor["source"] + source_writes = [event for event in history if event["guest"] == source and event["op"] == "create"] + assert len(source_writes) == 2, source_writes + initial, overwrite = source_writes + assert initial["first"] == "8", initial + assert overwrite["first"] == ("8" if scenario == "wrong-srv-offset" else "4"), overwrite + assert overwrite["old"] == initial["new"], overwrite + bound = [event for event in history if event["guest"] == destination] + assert bound[0]["op"] == "create" and bound[0]["resource"] == "0", bound + if scenario == "missing-copy": + assert len(bound) == 1, bound + else: + assert bound[1]["op"] == "copy" and bound[1]["source"] == source, bound + assert bound[1]["new"] == initial["new"], bound + if scenario == "stale-copy": + assert len(bound) == 2 and bound[-1]["new"] != overwrite["new"], bound + else: + assert bound[-1]["op"] == "copy" and bound[-1]["new"] == overwrite["new"], bound + assert int(bound[-1]["seq"]) > int(overwrite["seq"]), bound + final = bound[-1] + assert final["desktop"] == descriptor["desktop"], final + assert int(final["guest"], 16) != int(final["desktop"], 16), final + magic, token = descriptor["token_bound"].split(",") + assert magic == "56573258" and int(token) + 1 == int(final["new"]), descriptor + for event in history: + assert event["slot"] == "18" and event["materialized"] == "1", event + assert event["guest_read"] == "1" and event["guest_bytes"] == "32", event + if event["resource"] != "0": + assert int(event["backing"], 16) == int(descriptor["input"], 16), event + if event["old"] != "0": + previous = event["guest_before"].split(",") + assert previous[0] == "56573258" and int(previous[1], 16) + 1 == int(event["old"]), event + + +def check(executable, adapter, scenario, trace=True): + env = dict(os.environ) + env["X2W_MESH_PROVENANCE_CASE"] = scenario + if trace: + env["X2W_D3D12_DESCRIPTOR_HISTORY"] = "1" + else: + env.pop("X2W_D3D12_DESCRIPTOR_HISTORY", None) + # Always inspect this process's stderr, not a caller's persistent trap log. + env.pop("X2W_TRAP_LOG", None) + result = subprocess.run([str(executable), adapter, "mesh-provenance"], env=env, + capture_output=True, text=True, timeout=45) + if result.returncode == 77: + print(result.stdout, end="") + return False + print(result.stdout, end="") + assert result.returncode == 0, (scenario, result.returncode, result.stdout, result.stderr) + assert "DEVICE REMOVED" not in result.stderr and "ExecuteIndirect refused" not in result.stderr, result.stderr + records = observations(result.stdout, "provenance record ") + assert len(records) == 2 and [r["phase"] for r in records] == ["post-write", "pre-consume"], records + summary, = observations(result.stdout, "provenance result ") + assert positive_oracle(records, summary) == (scenario == "positive"), (scenario, records, summary) + assert summary["changed"] == ("8" if scenario == "positive" else "0"), summary + fences = observations(result.stdout, "provenance fence ") + assert [event["value"] for event in fences] == ["1", "2", "3"], fences + assert len({event["queue"] for event in fences}) == len({event["fence"] for event in fences}) == 1, fences + assert all(int(event["completed"]) >= int(event["value"]) for event in fences), fences + producer, = observations(result.stdout, "provenance producer ") + consumer, = observations(result.stdout, "provenance consumer ") + assert producer["queue"] == consumer["queue"] == fences[0]["queue"], (producer, consumer) + assert producer["resource"] == consumer["resource"] == records[0]["resource"] == records[1]["resource"], records + assert producer["offset"] == records[0]["offset"] == "4", records + assert consumer["offset"] == records[1]["offset"] == ("20" if scenario == "wrong-argument-offset" else "4"), records + assert producer["bytes"] == consumer["bytes"] == "12", (producer, consumer) + write, = observations(result.stdout, "provenance input-write ") + scalar, = observations(result.stdout, "provenance input-record ") + descriptor, = observations(result.stdout, "provenance descriptor ") + assert write["queue"] == producer["queue"], write + assert int(write["resource"], 16) == int(scalar["resource"], 16) == int(descriptor["input"], 16), scalar + assert write["offset"] == scalar["offset"] == "16" and write["value"] == scalar["value"] == "2", scalar + assert scalar["adjacent_offset"] == "32" and scalar["adjacent_value"] == "0", scalar + assert result.stdout.index("provenance record phase=post-write") < result.stdout.index("provenance consumer ") + if trace: + check_history(result.stdout, result.stderr, scenario) + else: + assert "x2w-descriptor-history " not in result.stderr, result.stderr + return True + + +def main(): + executable = Path(sys.argv[1]).resolve() + adapter = sys.argv[2] + for scenario in CASES: + if not check(executable, adapter, scenario): + return 77 + assert check(executable, adapter, "positive", trace=False) + print("Mesh argument provenance: positive, four negative controls and trace opt-out passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main())