Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CMakePresets.json
Original file line number Diff line number Diff line change
Expand Up @@ -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)$"
}
}
},
Expand Down
155 changes: 155 additions & 0 deletions docs/experiments/mesh-argument-provenance.md
Original file line number Diff line number Diff line change
@@ -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`.
1 change: 1 addition & 0 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
57 changes: 57 additions & 0 deletions src/startup_stubs/d3d12_capture.inl
Original file line number Diff line number Diff line change
Expand Up @@ -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<const void*>(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,
Expand Down Expand Up @@ -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.
Expand All @@ -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(&note_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
Expand Down
10 changes: 10 additions & 0 deletions tests/cmake/mesh_argument_provenance.cmake
Original file line number Diff line number Diff line change
@@ -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"
"$<TARGET_FILE:startup_indirect_draw_indexed>" ${adapter})
set_tests_properties(startup_mesh_argument_provenance_${adapter} PROPERTIES
TIMEOUT 120 SKIP_RETURN_CODE 77)
endforeach()
endif()
8 changes: 7 additions & 1 deletion tests/startup_indirect_draw_indexed.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -2440,6 +2443,9 @@ int main(int argc, char** argv) try
ComPtr<ID3D12CommandSignature> 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,
Expand Down
Loading
Loading