From 928b9d10aebde4fbc939f7ec7288aaa26a44ccd9 Mon Sep 17 00:00:00 2001 From: sagudev <16504129+sagudev@users.noreply.github.com> Date: Wed, 23 Sep 2026 19:38:07 +0200 Subject: [PATCH] better safety on BufferMapping Signed-off-by: sagudev <16504129+sagudev@users.noreply.github.com> --- deno_webgpu/buffer.rs | 5 +-- player/tests/player/main.rs | 5 +-- wgpu-core/src/resource.rs | 74 +++++++++++++++++++++++++++-------- wgpu/src/backend/wgpu_core.rs | 2 + 4 files changed, 63 insertions(+), 23 deletions(-) diff --git a/deno_webgpu/buffer.rs b/deno_webgpu/buffer.rs index 02c8ac4e4..891668b6b 100644 --- a/deno_webgpu/buffer.rs +++ b/deno_webgpu/buffer.rs @@ -235,10 +235,7 @@ impl GPUBuffer { ) } } else { - // SAFETY: buffer is mapped for read - // FIXME: but there are overlapping views - let slice = unsafe { mapping.slice() }; - let vec = slice.to_vec(); + let vec = mapping.read_into_vec(0); drop(mapping); v8::ArrayBuffer::new_backing_store_from_vec(vec) diff --git a/player/tests/player/main.rs b/player/tests/player/main.rs index 486bbfa06..3a8cb7099 100644 --- a/player/tests/player/main.rs +++ b/player/tests/player/main.rs @@ -137,9 +137,8 @@ impl Test<'_> { .collect::>(), }; - // SAFETY: Buffer is mapped for read and this is only mapping - let contents = unsafe { mapping.slice() }; - if &expected_data[..] != contents { + let contents = mapping.read_into_vec(0); + if expected_data[..] != contents { panic!( "Test expectation is not met!\nBuffer content was:\n{contents:?}\nbut expected:\n{expected_data:?}" ); diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index 9e82ee403..1926a9ebb 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -1,4 +1,10 @@ -use alloc::{borrow::Cow, borrow::ToOwned as _, boxed::Box, string::String, sync::Arc, vec::Vec}; +use alloc::{ + borrow::{Cow, ToOwned as _}, + boxed::Box, + string::String, + sync::Arc, + vec::Vec, +}; use core::{ borrow::Borrow, fmt, @@ -12,7 +18,7 @@ use thiserror::Error; use wgt::{ error::{ErrorType, WebGpuError}, math::align_to, - MapMode, TextureSelector, + MapMode, TextureSelector, WriteOnly, }; #[cfg(feature = "trace")] @@ -274,19 +280,21 @@ unsafe impl Sync for BufferMapState {} pub struct BufferMapping { ptr: NonNull, len: u64, + mode: MapMode, // guard needs to be dropped before the lock _guard: wgpu_sync::RwLockReadGuard<'static, BufferMapState>, _lock: Arc>, } impl BufferMapping { - fn new(ptr: NonNull, len: u64, lock: Arc>) -> Self { + fn new(ptr: NonNull, len: u64, mode: MapMode, lock: Arc>) -> Self { // SAFETY: We want to bypass the lock ranking system here, // because the lock is exposed to users. let guard = unsafe { lock.underlying() }.read(); Self { ptr, len, + mode, // SAFETY: Guard is tied to the lifetime of the lock, // and it will be dropped before the lock. _guard: unsafe { @@ -301,27 +309,55 @@ impl BufferMapping { /// ### How to safely use the pointer /// - /// - No other overlapping mapped range should be accessed simultaneously. /// - Pointer is only accessed for the length returned by [`BufferMapping::len`]. - /// - Writing to a [`wgt::BufferUsages::MAP_READ`] buffer can have unexpected results (visible in GPU only if it's coherent). - /// - Reading [`wgt::BufferUsages::MAP_WRITE`] buffer with [`wgt::Features::MAPPABLE_PRIMARY_BUFFERS`] feature enabled - /// can have unexpected results due to write combing. + /// - Pointer is only accessed while [`BufferMapping`] is alive. + /// - Reading is allowed if [`BufferMapping::mode`] is [`MapMode::Read`] (buffer has [`wgt::BufferUsages::MAP_READ`] set). + /// - Writing is allowed if [`BufferMapping::mode`] is [`MapMode::Write`] (buffer has [`wgt::BufferUsages::MAP_WRITE`] set). + /// - Atomics must not be used through the pointer since read-modify-write operations may not function on write-combining memory. + /// This also means that it's not safe to create rust references from this pointer since rust's memory model requires atomic operations to work. pub fn ptr(&self) -> NonNull { self.ptr } + pub fn mode(&self) -> MapMode { + self.mode + } + #[expect(clippy::len_without_is_empty)] pub fn len(&self) -> u64 { self.len } - /// # Safety - /// - /// - No other overlapping mapped range should be accessed simultaneously. - /// - Buffer was mapped with [`wgt::BufferUsages::MAP_READ`] or with [`wgt::BufferUsages::MAP_WRITE`] but without [`wgt::Features::MAPPABLE_PRIMARY_BUFFERS`], - /// otherwise one can have unexpected results due to write combing - pub unsafe fn slice(&self) -> &[u8] { - unsafe { core::slice::from_raw_parts(self.ptr().as_ptr(), self.len() as usize) } + /// Read the contents of the mapped buffer from `offset` into a `Vec`. + /// [`BufferMapping::mode`] must be [`MapMode::Read`] (buffer has [`wgt::BufferUsages::MAP_READ`] set) otherwise it will panic. + pub fn read_into_vec(&self, offset: usize) -> Vec { + assert!(self.mode == MapMode::Read); + assert!(offset <= self.len as usize); + let mut vec = alloc::vec![0u8; self.len as usize - offset]; + self.read(&mut vec, offset); + vec + } + + /// Read the contents of the mapped buffer into `dst` starting from `offset`. + /// [`BufferMapping::mode`] must be [`MapMode::Read`] (buffer has [`wgt::BufferUsages::MAP_READ`] set) otherwise it will panic. + pub fn read(&self, dst: &mut [u8], offset: usize) { + assert!(self.mode == MapMode::Read); + let size = self.len - offset as u64; + assert!(dst.len() <= size as usize); + unsafe { + core::ptr::copy_nonoverlapping( + self.ptr.as_ptr().add(offset), + dst.as_mut_ptr(), + dst.len(), + ) + }; + } + + /// Returns a write-only slice to the mapped buffer. + /// [`BufferMapping::mode`] must be [`MapMode::Write`] (buffer has [`wgt::BufferUsages::MAP_WRITE`] set) otherwise it will panic. + pub fn write_slice(&'_ self) -> WriteOnly<'_, [u8]> { + assert!(self.mode == MapMode::Write); + unsafe { WriteOnly::new(NonNull::slice_from_raw_parts(self.ptr, self.len as usize)) } } } @@ -995,12 +1031,17 @@ impl Buffer { } let ptr = unsafe { staging_buffer.ptr() }; let ptr = unsafe { NonNull::new_unchecked(ptr.as_ptr().offset(offset as isize)) }; - Ok(BufferMapping::new(ptr, range_size, self.map_state.clone())) + Ok(BufferMapping::new( + ptr, + range_size, + MapMode::Write, + self.map_state.clone(), + )) } BufferMapState::Active { ref mapping, ref range, - .. + ref host, } => { if offset > range.end { return Err(BufferAccessError::OutOfBoundsStartOffsetOverrun { @@ -1028,6 +1069,7 @@ impl Buffer { Ok(BufferMapping::new( NonNull::new_unchecked(mapping.ptr.as_ptr().offset(relative_offset)), range_size, + *host, self.map_state.clone(), )) } diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index 8a5288ece..516bb0e67 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -2976,6 +2976,8 @@ impl dispatch::BufferMappedRangeInterface for CoreBufferMappedRange { #[inline] unsafe fn read_slice(&self) -> &[u8] { + // FIXME: We currently tolerate this + // https://github.com/gfx-rs/wgpu/pull/10307#discussion_r4093841117 unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.size) } }