Skip to content

GPU: guard subresource and region bounds in texture copies and MSAA resolves - #2047

Open
fuzeofficlal wants to merge 1 commit into
Marvisak:mainfrom
fuzeofficlal:fix/gpu-copy-resolve-subresource-box-bounds
Open

fuzeofficlal wants to merge 1 commit into
Marvisak:mainfrom
fuzeofficlal:fix/gpu-copy-resolve-subresource-box-bounds

Conversation

@fuzeofficlal

Copy link
Copy Markdown
Contributor

Summary

  • Validate subresource indices (including planar depth/stencil copies), mip and footprint extents, block alignment, empty or inverted D3D12_BOX regions, destination coordinates, sample counts, subresource dimensions, same-host-texture aliases, and element sizes before recording CopyTextureRegion, CopyResource, or ResolveSubresource on the host command list.
  • Return early on out-of-bounds or incompatible calls before transitioning resources or allocating upload memory instead of triggering D3D12 debug layer errors, faults, or device removal.

Testing

  • VICTORY_D3D12_DEBUG=1 cargo test -p victory-gpu --lib --locked -- copy_and_resolve_reject (verified on NVIDIA RTX 5090, AMD Radeon Graphics, and D3D12 WARP with 0 debug errors)
  • VICTORY_D3D12_WARP=1 cargo test -p victory-gpu --features diagnostics --locked
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
  • cargo xtask policy

@jeremygold02

Copy link
Copy Markdown
Contributor

Triage verdict — Keep the bounds checks, retain valid MSAA copies and regional resolves (eb6f971)

Evidence

  • @fuzeofficlal’s early validation avoids sending malformed regions to D3D12, but CopyTextureRegion now rejects every multisampled source or destination. D3D12 permits a whole copy between compatible multisampled subresources with matching sample counts, zero destination offsets, and a null source box. Wrapper guards · D3D12 copy contract
  • The equal-extent check also runs before the existing regional resolve branch, which deliberately clips a larger source to the destination. Keep that path separate from the validation for full ResolveSubresource. Resolve check · Regional path

Checks and limits

  • On native D3D12, a disposable extension of the submitted fixture exercised two distinct 8×8, 4× MSAA textures. The wrapper copy followed by resolve left all 64 pixels at the old destination color. The direct D3D12 copy with the same whole-subresource arguments followed by resolve produced the source color in all 64 pixels. The regional resolve finding is static.

Next step

  • Retain valid whole MSAA copies and the bounded regional resolve, with positive readback tests for both. Keep the invalid cases. Coordinate the same-resource check with GPU: track texture subresource states #594 so a distinct subresource copy can be preserved when per-subresource state tracking lands.

This verification was AI-assisted.

@catminou4 catminou4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review only: victory-gpu is Windows-only (D3D12/windows_sys) — nothing compiles or runs on macOS; source review of the diff.

Subresource/region bounds guarded in texture copies — memory-safety hardening on the copy path.

@fuzeofficlal
fuzeofficlal force-pushed the fix/gpu-copy-resolve-subresource-box-bounds branch from eb6f971 to af6e4a0 Compare November 25, 2026 04:41
@fuzeofficlal

Copy link
Copy Markdown
Contributor Author

Updated in af6e4a0e — thanks @jeremygold02 for catching both cases:

  • CopyTextureRegion multisampled whole-subresource copies: SUBRESOURCE -> SUBRESOURCE copies with SampleDesc.Count > 1 now run when SampleDesc matches, source_box is null, (x, y, z) == (0, 0, 0), and the source/destination subresource extents match (while FOOTPRINT and sub-box/offset MSAA copies remain rejected).
  • Regional ResolveSubresourceRegion clipping: resolve_extents now returns (dst_size, src_size) for the selected subresources rather than requiring equal extents up front, routing dst_size == src_size to ResolveSubresource and mismatched extents to ResolveSubresourceRegion clipped to min(dst_size, src_size).
  • Added end-to-end D3D12 debug-layer readback coverage for whole-subresource 4x MSAA CopyTextureRegion and both full and clipped ResolveSubresourceRegion paths across RTX 5090, AMD RDNA2, and WARP.

Marvisak commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Merge candidate. copy_resource, copy_texture_region and resolve in crates/victory-gpu/src/list.rs now check subresource indices (including the second depth/stencil plane), box and destination bounds, block alignment, sample counts and element sizes before recording. Whole-subresource MSAA copies and the clipped ResolveSubresourceRegion path are kept. I re-read the subresource arithmetic and block rounding in subresource_extent against resource::element, pc_format and family on main, and they agree. CI passes (check).

On your reply: bd6b3f9 addresses all three points. Each rejection now logs once through warn_once! (an empty box is a silent no-op, as in D3D12), the redundant same-resource check in resolve_extents is gone, and the shared-host-texture rejection carries a shortcut: note pointing to #594. @Venom2054's run, which logged 48 CopyResource state errors from aliased title objects sharing one host texture and none with the guard, gives real evidence for that guard. The other checks have no runtime case yet, but a false reject now shows up in the log. The change from passing format straight through to pc_format(format) in resolve is small and maps the console-only depth formats, so I see no problem with it. The supplemental alias tests in that comment would be a useful addition but are not required.


Generated by Claude Code

…esolves

Validate subresource indices (including planar depth and stencil copies), mip and footprint extents, block alignment, destination coordinates, sample counts, and element sizes before recording CopyTextureRegion, CopyResource, ResolveSubresource, or ResolveSubresourceRegion on the host command list.

Empty CopyTextureRegion source boxes (left >= right, top >= bottom, or front >= back) return silently per the D3D12 specification, while every non-empty rejection logs once per reason so dropped copies from host translation mismatches (such as shared placed textures in resource::shared_texture before per-subresource tracking Marvisak#594, console 16-bit depth-stencil format translation, or mismatched mip/extent host textures) remain visible.

Whole-subresource multisampled CopyTextureRegion calls with matching sample descriptions, zero destination offsets, and a null source box continue to run, and mismatched resolve subresource extents route to the regional clipping path while out-of-bounds or incompatible calls return before transitioning resources or allocating upload memory.
@fuzeofficlal
fuzeofficlal force-pushed the fix/gpu-copy-resolve-subresource-box-bounds branch from af6e4a0 to bd6b3f9 Compare November 25, 2026 10:04
@fuzeofficlal

Copy link
Copy Markdown
Contributor Author

Updated in bd6b3f98 per triage feedback:

  1. Once-per-reason diagnostic logging (warn_once!):
    • Every non-empty rejection in copy_resource, copy_texture_region, resolve_extents, and resolve now logs once via tracing::warn! with structured fields (matching copy_buffer_region's "copy outside its buffer" pattern).
    • Separated empty source_box (left >= right || top >= bottom || front >= back) as a silent documented D3D12 no-op, and verified with a custom tracing subscriber in copy_and_resolve_reject_out_of_bounds_subresources_and_boxes that empty boxes emit 0 warnings while repeated out-of-bounds boxes emit 1 warning.
  2. Removed unreachable check & documented #594 shortcut:
    • Dropped the redundant same-resource check and unused title pointers from resolve_extents (a.SampleDesc.Count != 1 || b.SampleDesc.Count <= 1 already excludes resolving a texture to itself).
    • Added a // shortcut: ... (#594) comment on the shared-host-texture rejection in copy_texture_region explaining that copying between distinct subresources of one texture (or aliased title textures sharing a HostTexture via resource::shared_texture) requires per-subresource state tracking (#594) because HostList::transition currently tracks whole textures.
  3. Translation mismatch paths motivating the remaining checks:
    • Shared host textures across aliased placed resources (resource::shared_texture / memory_key + takes) and #594 whole-texture state transitions (dst.resource == src.resource or ptr::eq(to, texture)).
    • Console 1-plane to PC 2-plane depth-stencil translation (pc_format 118..=120 -> 45..=47, changing plane counts and plane element byte sizes) and host_desc typeless/castable format selection (subresource_extent, elem match, and resolve_extents format-family checks).
    • Console regional MSAA resolves where source and destination extents differ (resolve_extents routing mismatched extents to ResolveSubresourceRegion instead of ResolveSubresource).

@Venom2054

Copy link
Copy Markdown

Native Windows/NVIDIA evidence for the whole-resource shared-host-texture guard, plus two supplemental regression tests for bd6b3f9.

RTX 5070 Ti 16 GB, driver 621.01; i7-14700, 32 GB RAM, Windows 11 Pro 26200.

Runtime motivation: before the guard, a D3D12 debug run logged 48 ID 538 errors from CopyResource: the 2560x1440, format 19 depth texture destination was in COPY_SOURCE rather than COPY_DEST (planes/subresources 0 and 1). I independently narrowed this down to distinct title objects sharing one host resource, then found the equivalent guard already in this PR.

With only the equivalent whole-CopyResource early return added to the local integration stack, the guard's once-only diagnostic fired during the title run. The 345.7-second debug run had zero texture ID 538 errors and no logged device removal. It was stopped manually. This is evidence for this particular guard, not validation of every check in the larger PR. Frames reached differ, so these counts are observational, not a benchmark. Buffer state errors and shader translation refusals remain; rendering is still severely malformed and not playable. A preceding attempt ended early without a captured exit code or logged GPU-removal message; it is not counted as a successful stability run.

Synthetic validation, independently on this PR's exact head plus the two tests below:

  • All 7 list::tests pass on NVIDIA with VICTORY_D3D12_DEBUG=1.
  • All 7 also pass with VICTORY_D3D12_WARP=1 and the debug layer enabled.
  • This includes the existing bounds/MSAA/resolve fixture and its readbacks.
  • The new alias test covers different title handles sharing a host texture, exact self-copy, CopyResourceX, colour and depth/stencil, both host_written values, no staging allocation, unchanged state, and preserving the first real texture use.
  • The positive control checks all 32x32 RGBA8 pixels after a self-copy no-op followed by a real copy to a distinct host texture. The alias regression failed before the guard because host_written changed from false to true.

The same two tests also pass on main 940d32f with only the narrow guard added (hardware and WARP). Separately, the combined local stack passes 752 workspace tests (11 ignored) and 166 GPU debug tests (3 ignored), build, Clippy with -D warnings, and asset policy. Those combined-stack counts are not claimed for this PR alone.

Runtime stack for reproducibility: main 940d32f, #2177 plus a local fallback fix, GPU commit 93c4e18 from #1926, #1762, #1906, #2098, #89, #189, #1152, #1803, #2276 and #2155, then the narrow equivalent guard. Wave64 auto selected Emulate; GPU timing off, default loop limit, no skipped pipelines. The full #2047 was used for the isolated synthetic tests, not for this title run.

The patch below adds only the two synthetic tests to bd6b3f9. No game data, private paths, screenshots or raw logs are included. This is supplemental evidence for the existing PR, not a claim to have originated its guard. Integration and test authoring were assisted by OpenAI Codex.

Supplemental test-only patch against bd6b3f9
diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs
index 4e20aae..11d6fb5 100644
--- a/crates/victory-gpu/src/list.rs
+++ b/crates/victory-gpu/src/list.rs
@@ -3047,4 +3047,221 @@ mod tests {
         }
         assert_eq!(DEBUG_ERRORS.load(Ordering::Relaxed), 0);
     }
+
+    #[cfg(windows)]
+    #[test]
+    fn whole_texture_copies_skip_shared_host_resources() {
+        use windows::core::Interface;
+        let Some(host) = crate::host::host() else {
+            return;
+        };
+        let null = std::ptr::null();
+        let iid = crate::object::guid(
+            0x696442be,
+            0xa72e,
+            0x4059,
+            [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad],
+        );
+        let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
+        let mut allocator = null;
+        assert_eq!(
+            create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
+            S_OK
+        );
+        let mut list = null;
+        assert_eq!(
+            create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list),
+            S_OK
+        );
+        let hl = host_list(list).expect("a host command list");
+
+        // Distinct title objects at one address share a host texture. Cover
+        // both CPU-uploaded colour and the two-plane depth/stencil case.
+        for (format, flags) in [(28u32, 0u32), (118, 2)] {
+            let layout = std::alloc::Layout::from_size_align(1 << 20, 1 << 16).unwrap();
+            // SAFETY: a nonzero layout; title texture caches retain this memory.
+            let memory = unsafe { std::alloc::alloc_zeroed(layout) };
+            assert!(!memory.is_null());
+            let words = [
+                3,
+                0,
+                0,
+                0,
+                32,
+                0,
+                32,
+                1 | 1 << 16,
+                format,
+                1,
+                0,
+                0,
+                flags,
+                0,
+            ];
+            let make = || {
+                let mut out = null;
+                assert_eq!(
+                    crate::resource::create_at_address(
+                        null,
+                        memory as u64,
+                        words.as_ptr().cast(),
+                        0,
+                        null.cast(),
+                        &iid,
+                        &mut out,
+                    ),
+                    S_OK
+                );
+                out
+            };
+            let (first, alias) = (make(), make());
+            assert_ne!(first, alias);
+            let a = crate::resource::host_copy(first).unwrap();
+            let b = crate::resource::host_copy(alias).unwrap();
+            assert_eq!(a.texture.as_raw(), b.texture.as_raw());
+            let initial = a.state.load(Ordering::Relaxed);
+            for written in [false, true] {
+                a.host_written.store(written, Ordering::Relaxed);
+                copy_resource(list, alias, first);
+                copy_resource_x(list, first, alias, 0);
+                copy_resource(list, first, first);
+                // A no-op must not suppress a later upload from title memory,
+                // allocate staging, or claim the list's first real texture use.
+                assert_eq!(a.host_written.load(Ordering::Relaxed), written);
+                assert!(a.staging.lock().unwrap().is_none());
+                assert!(hl.first_use(a.texture.as_raw() as usize));
+                assert_eq!(close(list), S_OK);
+                host.execute(&[hl]);
+                assert_eq!(host.log_messages(), None);
+                assert_eq!(a.state.load(Ordering::Relaxed), initial);
+                assert_eq!(reset(list, allocator, null), S_OK);
+            }
+            for object in [alias, first] {
+                assert_eq!(release(object), 0);
+            }
+        }
+        for object in [list, allocator] {
+            assert_eq!(release(object), 0);
+        }
+    }
+
+    #[cfg(windows)]
+    #[test]
+    fn whole_texture_copies_between_distinct_hosts_preserve_pixels() {
+        use windows::Win32::Graphics::Direct3D12::*;
+        let Some(host) = crate::host::host() else {
+            return;
+        };
+        let null = std::ptr::null();
+        let iid = crate::object::guid(
+            0x696442be,
+            0xa72e,
+            0x4059,
+            [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad],
+        );
+        let make = || {
+            let heap = [1u32, 0, 0, 0, 0];
+            let words = [3u32, 0, 0, 0, 32, 0, 32, 1 | 1 << 16, 28, 1, 0, 0, 1, 0];
+            let mut out = null;
+            assert_eq!(
+                crate::resource::create_committed(
+                    null,
+                    heap.as_ptr().cast(),
+                    0,
+                    words.as_ptr().cast(),
+                    0,
+                    null.cast(),
+                    &iid,
+                    &mut out,
+                ),
+                S_OK
+            );
+            out
+        };
+        let (src, dst) = (make(), make());
+        let from = crate::resource::host_resource(src).unwrap();
+        let to = crate::resource::host_resource(dst).unwrap();
+        assert_ne!(from, to);
+        let mut allocator = null;
+        assert_eq!(
+            create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
+            S_OK
+        );
+        let mut list = null;
+        assert_eq!(
+            create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list),
+            S_OK
+        );
+        let hl = host_list(list).unwrap();
+        ensure_state(hl, src, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32);
+        // SAFETY: a live render target and an open list; its prelude sets the state.
+        unsafe {
+            hl.list
+                .ClearRenderTargetView(host.rtv(from, None), &[1.0, 0.0, 1.0, 1.0], None)
+        };
+        crate::texture::host_written(src);
+        copy_resource(list, src, src);
+        copy_resource_x(list, dst, src, 0);
+        assert!(
+            crate::resource::host_copy(dst)
+                .unwrap()
+                .host_written
+                .load(Ordering::Relaxed)
+        );
+
+        let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
+        let mut bytes = 0;
+        // SAFETY: plain queries on a live texture with one subresource.
+        unsafe {
+            host.device.GetCopyableFootprints(
+                &to.GetDesc(),
+                0,
+                1,
+                0,
+                Some(&mut footprint),
+                None,
+                None,
+                Some(&mut bytes),
+            )
+        };
+        let (output, mapped) = host.shared_buffer(bytes).unwrap();
+        let read_to = D3D12_TEXTURE_COPY_LOCATION {
+            // SAFETY: a borrowed COM pointer; output stays live through submission.
+            pResource: unsafe { std::mem::transmute_copy(&output) },
+            Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
+            Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
+                PlacedFootprint: footprint,
+            },
+        };
+        let read_from = D3D12_TEXTURE_COPY_LOCATION {
+            // SAFETY: a borrowed COM pointer; dst stays live through submission.
+            pResource: unsafe { std::mem::transmute_copy(to) },
+            Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
+            Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
+                SubresourceIndex: 0,
+            },
+        };
+        ensure_state(hl, dst, COPY_SOURCE);
+        // SAFETY: valid locations and states; the buffer promotes to COPY_DEST.
+        unsafe {
+            hl.list
+                .CopyTextureRegion(&read_to, 0, 0, 0, &read_from, None)
+        };
+        assert_eq!(close(list), S_OK);
+        host.execute(&[hl]);
+        assert_eq!(host.log_messages(), None);
+        for y in 0..32usize {
+            for x in 0..32usize {
+                let at = y * footprint.Footprint.RowPitch as usize + x * 4;
+                // SAFETY: within the mapped footprint; execute waits for completion.
+                let pixel = unsafe { std::slice::from_raw_parts(mapped.add(at), 4) };
+                assert_eq!(pixel, [255, 0, 255, 255], "pixel ({x}, {y})");
+            }
+        }
+        assert_eq!(reset(list, allocator, null), S_OK);
+        let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
+        for object in [dst, src, list, allocator] {
+            assert_eq!(release(object), 0);
+        }
+    }
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants