From d7220bf2f09fc2aaf39b77c1f65faa4473ef4904 Mon Sep 17 00:00:00 2001 From: sagudev <16504129+sagudev@users.noreply.github.com> Date: Thu, 24 Sep 2026 16:27:16 +0200 Subject: [PATCH] [wgpu] forbid read BufferViews on MapMode::Write mapped buffers Signed-off-by: sagudev <16504129+sagudev@users.noreply.github.com> --- CHANGELOG.md | 6 ++ tests/tests/wgpu-gpu/buffer.rs | 10 --- tests/tests/wgpu-gpu/buffer_usages.rs | 12 +++- .../wgpu-validation/api/buffer_mapping.rs | 8 ++- wgpu/src/api/buffer.rs | 64 +++++++++++++------ wgpu/src/api/device.rs | 10 ++- wgpu/src/backend/wgpu_core.rs | 7 +- 7 files changed, 75 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3effffeec..1cebc049c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -95,6 +95,12 @@ as it could trigger buffer destruction and thus unmapping in case the device is By @sagudev in [#10307](https://github.com/gfx-rs/wgpu/pull/10307). +#### `BufferView` are not supported on `MapMode::Write` mapped buffers + +`MapMode::Write` mapped buffers are not supported to create `BufferView`s (read only mapping) from them. + +By @sagudev in [#10307](https://github.com/gfx-rs/wgpu/pull/10307). + ### Added/New Features #### General diff --git a/tests/tests/wgpu-gpu/buffer.rs b/tests/tests/wgpu-gpu/buffer.rs index 32c65edc4..263b94645 100644 --- a/tests/tests/wgpu-gpu/buffer.rs +++ b/tests/tests/wgpu-gpu/buffer.rs @@ -91,11 +91,6 @@ async fn test_empty_buffer_range_with_usage( .await .unwrap(); - { - let view = b0.slice(0..0).get_mapped_range().unwrap(); - assert!(view.is_empty()); - } - { let view = b0.slice(0..0).get_mapped_range_mut().unwrap(); assert!(view.is_empty()); @@ -117,11 +112,6 @@ async fn test_empty_buffer_range_with_usage( mapped_at_creation: true, }); - { - let view = b1.slice(0..0).get_mapped_range().unwrap(); - assert!(view.is_empty()); - } - if usage.contains(wgpu::BufferUsages::MAP_WRITE) { let view = b1.slice(0..0).get_mapped_range_mut().unwrap(); assert!(view.is_empty()); diff --git a/tests/tests/wgpu-gpu/buffer_usages.rs b/tests/tests/wgpu-gpu/buffer_usages.rs index 82dace183..a6b459f65 100644 --- a/tests/tests/wgpu-gpu/buffer_usages.rs +++ b/tests/tests/wgpu-gpu/buffer_usages.rs @@ -161,9 +161,15 @@ async fn map_test( .unwrap(); if !before_unmap && !before_destroy { - { - let view = buffer.slice(0..size).get_mapped_range().unwrap(); - assert!(!view.is_empty()); + match map_mode_type { + Ma::Read => { + let view = buffer.slice(0..size).get_mapped_range().unwrap(); + assert!(!view.is_empty()); + } + Ma::Write => { + let view = buffer.slice(0..size).get_mapped_range_mut().unwrap(); + assert!(!view.is_empty()); + } } if after_unmap { diff --git a/tests/tests/wgpu-validation/api/buffer_mapping.rs b/tests/tests/wgpu-validation/api/buffer_mapping.rs index dcf225fc7..ec1b1661b 100644 --- a/tests/tests/wgpu-validation/api/buffer_mapping.rs +++ b/tests/tests/wgpu-validation/api/buffer_mapping.rs @@ -127,10 +127,14 @@ fn overlapping_ref_binding() { let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 1024, - usage: wgpu::BufferUsages::MAP_WRITE | wgpu::BufferUsages::COPY_SRC, - mapped_at_creation: true, + usage: wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, }); + buffer.map_async(wgpu::MapMode::Read, .., |_| {}); + + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let _mapping0 = buffer.slice(0..512).get_mapped_range().unwrap(); let _mapping1 = buffer.slice(256..768).get_mapped_range().unwrap(); } diff --git a/wgpu/src/api/buffer.rs b/wgpu/src/api/buffer.rs index 28de1d6e3..2dff9d599 100644 --- a/wgpu/src/api/buffer.rs +++ b/wgpu/src/api/buffer.rs @@ -483,7 +483,7 @@ impl Buffer { /// # Arguments /// /// - `core_buffer` - wgpu-core buffer. - /// - `mapped_range` - The range of the buffer that is currently mapped. If the buffer is not mapped, this should be `None`. + /// - `mapped_range` - Current state of mapped buffer if any. /// - `device` - The device that owns the buffer. /// /// # Panics @@ -496,7 +496,7 @@ impl Buffer { /// Changes to the wgpu-core buffer's state after this call may lead to undefined behavior if they are not compatible with the provided `mapped_range`. pub unsafe fn from_core( core_buffer: alloc::sync::Arc, - mapped_range: Option>, + mapped: Option, device: &Device, ) -> Self { use wgc::resource::ParentDevice; @@ -504,7 +504,7 @@ impl Buffer { core_buffer.same_device(&device.as_core().unwrap()).unwrap(); Self { inner: crate::backend::wgpu_core::CoreBuffer::from_core(core_buffer).into(), - map_context: MapContext::new(mapped_range, &device.buffers), + map_context: MapContext::new(mapped, &device.buffers), } } @@ -637,7 +637,7 @@ impl<'a> BufferSlice<'a> { callback: impl FnOnce(Result<(), BufferAsyncError>) + WasmNotSend + 'static, ) { let mut mc = self.buffer.map_context.lock(); - if mc.mapped_range.is_some() { + if mc.mapped.is_some() { // Buffer is already mapped; fail drop(mc); callback(Err(BufferAsyncError)); @@ -645,7 +645,10 @@ impl<'a> BufferSlice<'a> { } let end = self.offset + self.size; - mc.mapped_range = Some(self.offset..end); + mc.mapped = Some(MappingInfo { + range: self.offset..end, + kind: mode, + }); drop(mc); // release the lock of map_context as callback can call lock it again self.buffer @@ -812,19 +815,26 @@ impl fmt::Display for Subrange { } } +/// Represents information about current mapping. +#[derive(Debug)] +pub struct MappingInfo { + /// The range of the buffer that is mapped. + /// + /// All [`BufferView`]s and [`BufferViewMut`]s must fall within this range. + pub(crate) range: Range, + /// The mode in which the buffer is mapped. + pub(crate) kind: MapMode, +} + /// The mapped portion of a buffer, if any, and its outstanding views. /// /// This ensures that views fall within the mapped range and don't overlap. #[derive(Debug)] pub(crate) struct MapContext { - /// The range of the buffer that is mapped. - /// /// This becomes Some(...) when the buffer is mapped at creation time, and /// when you call `map_async` on some [`BufferSlice`] (so technically, it - /// indicates the portion that is *or has been requested to be* mapped.) - /// - /// All [`BufferView`]s and [`BufferViewMut`]s must fall within this range. - mapped_range: Option>, + /// indicates the data that is *or has been requested to be* mapped.) + mapped: Option, /// The ranges covered by all outstanding [`BufferView`]s and /// [`BufferViewMut`]s. These are non-overlapping, and are all contained @@ -866,6 +876,15 @@ impl WeakMapContext { } } +impl RangeMappingKind { + fn mode(&self) -> MapMode { + match self { + RangeMappingKind::Immutable => MapMode::Read, + RangeMappingKind::Mutable => MapMode::Write, + } + } +} + impl MapContext { /// Creates a new `MapContext`. /// @@ -874,11 +893,11 @@ impl MapContext { /// /// [`mapped_at_creation`]: BufferDescriptor::mapped_at_creation pub(crate) fn new( - mapped_range: Option>, + mapped: Option, device_buffers: &Arc>>, ) -> Arc> { let result = Arc::new(Mutex::new(Self { - mapped_range, + mapped, sub_ranges: Vec::new(), device_buffers: Arc::clone(device_buffers), })); @@ -890,7 +909,7 @@ impl MapContext { /// Record that the buffer is no longer mapped. fn reset(&mut self) { - self.mapped_range = None; + self.mapped = None; assert!( self.sub_ranges.is_empty(), @@ -904,19 +923,26 @@ impl MapContext { /// /// This returns an error if the given range is invalid. fn validate_and_add(&mut self, new_sub: Subrange) -> Result<(), MapRangeError> { - if self.mapped_range.is_none() { + let Some(mapped) = self.mapped.as_ref() else { return Err(MapRangeError( "tried to call get_mapped_range(_mut) on an unmapped buffer".into(), )); + }; + if mapped.kind != new_sub.kind.mode() { + return Err(MapRangeError(alloc::format!( + "tried to call get_mapped_range(_mut) on a buffer that was mapped for {:?}, \ + but the requested range is for {:?}", + mapped.kind, + new_sub.kind.mode() + ))); } - let mapped_range = self.mapped_range.as_ref().unwrap(); - if !range_contains(mapped_range, &new_sub.index) { + if !range_contains(&mapped.range, &new_sub.index) { return Err(MapRangeError(alloc::format!( "tried to call get_mapped_range(_mut) on a range that is not entirely mapped. \ Attempted to get range {}, but the mapped range is {}..{}", new_sub, - mapped_range.start, - mapped_range.end + mapped.range.start, + mapped.range.end ))); } // This check is essential for avoiding undefined behavior: it is the diff --git a/wgpu/src/api/device.rs b/wgpu/src/api/device.rs index afb9ee7d9..aa305d0d8 100644 --- a/wgpu/src/api/device.rs +++ b/wgpu/src/api/device.rs @@ -289,7 +289,10 @@ impl Device { #[must_use] pub fn create_buffer(&self, desc: &BufferDescriptor<'_>) -> Buffer { let map_context = MapContext::new( - desc.mapped_at_creation.then_some(0..desc.size), + desc.mapped_at_creation.then_some(MappingInfo { + range: 0..desc.size, + kind: MapMode::Write, + }), &self.buffers, ); @@ -620,7 +623,10 @@ impl Device { desc: &BufferDescriptor<'_>, ) -> Buffer { let map_context = MapContext::new( - desc.mapped_at_creation.then_some(0..desc.size), + desc.mapped_at_creation.then_some(MappingInfo { + range: 0..desc.size, + kind: MapMode::Write, + }), &self.buffers, ); diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index e08829685..4770a6187 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -2987,12 +2987,7 @@ impl dispatch::BufferMappedRangeInterface for CoreBufferMappedRange { #[inline] unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]> { - unsafe { - WriteOnly::new(NonNull::slice_from_raw_parts( - self.0.ptr(), - self.0.len() as usize, - )) - } + self.0.write_slice() } #[cfg(webgpu)]