From 61e76ee746bc6d8d5a378d0b608b4fb8fe1345f3 Mon Sep 17 00:00:00 2001 From: Andy Leiserson Date: Thu, 16 Apr 2026 05:27:01 -0700 Subject: [PATCH] fix(core): Use more checked arithmetic, part 2b (#9425) --- CHANGELOG.md | 4 ++ wgpu-core/src/command/bundle.rs | 4 +- wgpu-core/src/command/ray_tracing.rs | 87 +++++++++++++++++----------- wgpu-core/src/command/render.rs | 4 +- wgpu-core/src/device/ray_tracing.rs | 3 +- wgpu-core/src/ray_tracing.rs | 11 ++++ wgpu-hal/src/metal/device.rs | 5 +- wgpu-types/src/math.rs | 45 +++++++++----- wgpu-types/src/render.rs | 2 +- 9 files changed, 110 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e00e208b..529a5def0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,6 +108,10 @@ By @teoxoy in [#9351](https://github.com/gfx-rs/wgpu/pull/9351). - Passthrough shaders now require a list of entry points when being created. by @inner-daemons in [#9064](https://github.com/gfx-rs/wgpu/pull/9064). - BREAKING: The `dispatch` and `dispatch_indirect` methods on pass and bundle encoders have been renamed to `dispatch_workgroups` and `dispatch_workgroups_indirect`, respectively, to match the WebGPU spec. By @ErichDonGubler in [#9362](https://github.com/gfx-rs/wgpu/pull/9362). - `LoadOp::DontCare` can no longer be deserialized, and the `LoadOpDontCare` token no longer implements `Default`. This ensures that `DontCare` can only be used with `unsafe`, as intended. By @kpreid in [#9428](https://github.com/gfx-rs/wgpu/pull/9428). +- Minor changes to various error enums to support improved validation. By @andyleiserson in [#9357](https://github.com/gfx-rs/wgpu/pull/9357), [#9363](https://github.com/gfx-rs/wgpu/pull/9363), and [#9425](https://github.com/gfx-rs/wgpu/pull/9425): + - Added new `InvalidWorkgroupSizeError`, which is now used by `DrawError::InvalidGroupSize` and `StageError::InvalidWorkgroupSize`. + - Added `BuildAccelerationStructureError` variant `OffsetLimitedTo4GB` and changed `IndirectBufferOverrun` to contain offset and size rather than start and end offsets. + - `IndexFormat::byte_size` now returns `u32` instead of `usize`. #### Validation diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index 782b06c7c..1a39a5173 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -697,10 +697,10 @@ fn set_index_buffer( buffer.same_device(&state.device)?; buffer.check_usage(wgt::BufferUsages::INDEX)?; - if !offset.is_multiple_of(u64::try_from(index_format.byte_size()).unwrap()) { + if !offset.is_multiple_of(u64::from(index_format.byte_size())) { return Err(RenderCommandError::UnalignedIndexBuffer { offset, - alignment: index_format.byte_size(), + alignment: index_format.byte_size() as usize, } .into()); } diff --git a/wgpu-core/src/command/ray_tracing.rs b/wgpu-core/src/command/ray_tracing.rs index c4d6421cc..f8bba308b 100644 --- a/wgpu-core/src/command/ray_tracing.rs +++ b/wgpu-core/src/command/ray_tracing.rs @@ -213,7 +213,7 @@ pub(crate) fn build_acceleration_structures( state, )?; - let mut scratch_buffer_tlas_size = 0; + let mut scratch_buffer_tlas_size: u64 = 0; let mut tlas_storage = Vec::::with_capacity(tlas.len()); let mut instance_buffer_staging_source = Vec::::new(); @@ -222,15 +222,10 @@ pub(crate) fn build_acceleration_structures( state.tracker.tlas_s.insert_single(tlas.clone()); let scratch_buffer_offset = scratch_buffer_tlas_size; - assert!( - tlas.size_info.build_scratch_size - <= u64::MAX - - u64::from(state.device.alignments.ray_tracing_scratch_buffer_alignment) - ); - scratch_buffer_tlas_size += align_to( + scratch_buffer_tlas_size = scratch_buffer_tlas_size.saturating_add(align_to( tlas.size_info.build_scratch_size, u64::from(state.device.alignments.ray_tracing_scratch_buffer_alignment), - ); + )); let first_byte_index = instance_buffer_staging_source.len(); @@ -311,7 +306,9 @@ pub(crate) fn build_acceleration_structures( return Ok(()); }; - assert!(scratch_size.get() != u64::MAX); + if scratch_size.get() == u64::MAX { + return Err(crate::device::DeviceError::OutOfMemory.into()); + } let scratch_buffer = ScratchBuffer::new(state.device, scratch_size)?; @@ -775,11 +772,30 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>( }) { input_barriers.push(barrier); } - let index_stride = mesh.size.index_format.unwrap().byte_size() as u32; + let index_stride = mesh.size.index_format.unwrap().byte_size(); // `hal::AccelerationStructureTriangleIndices` accepts only `u32` offset - let vertex_offset = mesh.first_index.unwrap().saturating_mul(index_stride); - let indexes_size = - mesh.size.index_count.unwrap().saturating_mul(index_stride); + let Some(vertex_offset) = + mesh.first_index.unwrap().checked_mul(index_stride) + else { + return Err(BuildAccelerationStructureError::OffsetLimitedTo4GB { + buffer_ident: index_buffer.error_ident(), + offset: u64::from(mesh.first_index.unwrap()) + .saturating_mul(u64::from(index_stride)), + count: u64::from(mesh.first_index.unwrap()), + stride: u64::from(index_stride), + }); + }; + let Some(indexes_size) = + mesh.size.index_count.unwrap().checked_mul(index_stride) + else { + return Err(BuildAccelerationStructureError::OffsetLimitedTo4GB { + buffer_ident: index_buffer.error_ident(), + offset: u64::from(mesh.size.index_count.unwrap()) + .saturating_mul(u64::from(index_stride)), + count: u64::from(mesh.size.index_count.unwrap()), + stride: u64::from(index_stride), + }); + }; if mesh.size.index_count.unwrap() % 3 != 0 { return Err(BuildAccelerationStructureError::InvalidIndexCount( @@ -787,9 +803,7 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>( mesh.size.index_count.unwrap(), )); } - if indexes_size == u32::MAX - || vertex_offset == u32::MAX - || index_buffer.size < u64::from(vertex_offset) + if index_buffer.size < u64::from(vertex_offset) || index_buffer.size - u64::from(vertex_offset) < u64::from(indexes_size) { @@ -847,8 +861,15 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>( } // `hal::AccelerationStructureTriangleTransform` accepts only `u32` offset - let offset = u32::try_from(mesh.transform_buffer_offset.unwrap()) - .unwrap_or(u32::MAX); + let Ok(offset) = u32::try_from(mesh.transform_buffer_offset.unwrap()) + else { + return Err(BuildAccelerationStructureError::OffsetLimitedTo4GB { + buffer_ident: transform_buffer.error_ident(), + offset: mesh.transform_buffer_offset.unwrap(), + count: mesh.transform_buffer_offset.unwrap(), + stride: 1, + }); + }; if offset % wgt::TRANSFORM_BUFFER_ALIGNMENT as u32 != 0 { return Err( @@ -857,8 +878,7 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>( ), ); } - if offset == u32::MAX - || transform_buffer.size < 48 + if transform_buffer.size < 48 || transform_buffer.size - 48 < u64::from(offset) { return Err(BuildAccelerationStructureError::InsufficientBufferSize { @@ -915,13 +935,6 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>( { let scratch_buffer_offset = *scratch_buffer_blas_size; - assert!( - blas.size_info.build_scratch_size - <= u64::MAX - - u64::from( - state.device.alignments.ray_tracing_scratch_buffer_alignment - ) - ); *scratch_buffer_blas_size = scratch_buffer_blas_size.saturating_add(align_to( blas.size_info.build_scratch_size, u64::from(state.device.alignments.ray_tracing_scratch_buffer_alignment), @@ -1004,12 +1017,20 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>( } // `hal::AccelerationStructureAABBs` accepts only `u32` offset - let aabb_size = aabb - .size - .primitive_count - .saturating_mul(u32::try_from(aabb.stride).unwrap()); - if aabb_size == u32::MAX - || aabb_buffer.size < u64::from(aabb.primitive_offset) + let Some(aabb_size) = u32::try_from(aabb.stride) + .ok() + .and_then(|stride| aabb.size.primitive_count.checked_mul(stride)) + else { + return Err(BuildAccelerationStructureError::OffsetLimitedTo4GB { + buffer_ident: aabb_buffer.error_ident(), + offset: u64::from(aabb.size.primitive_count) + .saturating_mul(aabb.stride), + count: u64::from(aabb.size.primitive_count), + stride: aabb.stride, + }); + }; + + if aabb_buffer.size < u64::from(aabb.primitive_offset) || aabb_buffer.size - u64::from(aabb.primitive_offset) < u64::from(aabb_size) { diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 4c6633c10..46c75c7cd 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -2562,10 +2562,10 @@ fn set_index_buffer( buffer.check_usage(BufferUsages::INDEX)?; - if !offset.is_multiple_of(u64::try_from(index_format.byte_size()).unwrap()) { + if !offset.is_multiple_of(u64::from(index_format.byte_size())) { return Err(RenderCommandError::UnalignedIndexBuffer { offset, - alignment: index_format.byte_size(), + alignment: index_format.byte_size() as usize, } .into()); } diff --git a/wgpu-core/src/device/ray_tracing.rs b/wgpu-core/src/device/ray_tracing.rs index 47a70ab7c..da7c0da66 100644 --- a/wgpu-core/src/device/ray_tracing.rs +++ b/wgpu-core/src/device/ray_tracing.rs @@ -268,7 +268,8 @@ impl Device { let instance_buffer_size = self .alignments .raw_tlas_instance_size - .saturating_mul(desc.max_instances.max(1)); + .checked_mul(desc.max_instances.max(1)) + .expect("max_tlas_instance_count should not allow excessive buffer size"); let instance_buffer = unsafe { self.raw().create_buffer(&hal::BufferDescriptor { label: hal_label(Some("(wgpu-core) instances_buffer"), self.instance_flags), diff --git a/wgpu-core/src/ray_tracing.rs b/wgpu-core/src/ray_tracing.rs index 4df8d7ba5..05973a917 100644 --- a/wgpu-core/src/ray_tracing.rs +++ b/wgpu-core/src/ray_tracing.rs @@ -119,6 +119,16 @@ pub enum BuildAccelerationStructureError { buffer_size: BufferAddress, }, + #[error( + "Offset {offset}, computed as {count} times {stride} B, exceeds the maximum addressable offset 2^32 - 1 within buffer {buffer_ident:?}" + )] + OffsetLimitedTo4GB { + buffer_ident: ResourceErrorIdent, + offset: BufferAddress, + count: BufferAddress, + stride: BufferAddress, + }, + #[error("Buffer {0:?} associated offset doesn't align with the index type")] UnalignedIndexBufferOffset(ResourceErrorIdent), @@ -215,6 +225,7 @@ impl WebGpuError for BuildAccelerationStructureError { Self::MissingBufferUsage(e) => e.webgpu_error_type(), Self::MissingFeatures(e) => e.webgpu_error_type(), Self::InsufficientBufferSize { .. } + | Self::OffsetLimitedTo4GB { .. } | Self::UnalignedIndexBufferOffset(..) | Self::UnalignedTransformBufferOffset(..) | Self::InvalidIndexCount(..) diff --git a/wgpu-hal/src/metal/device.rs b/wgpu-hal/src/metal/device.rs index 061af6374..f13bb24c3 100644 --- a/wgpu-hal/src/metal/device.rs +++ b/wgpu-hal/src/metal/device.rs @@ -1397,7 +1397,10 @@ impl crate::Device for super::Device { .max() .unwrap_or(0); unsafe { - buffer_desc.setStride(wgt::math::align_to(stride as _, 4)) + buffer_desc.setStride(wgt::math::align_to( + NSUInteger::try_from(stride).unwrap(), + 4, + )) }; buffer_desc.setStepFunction(MTLVertexStepFunction::Constant); unsafe { buffer_desc.setStepRate(0) }; diff --git a/wgpu-types/src/math.rs b/wgpu-types/src/math.rs index d34e73ff6..e3d183794 100644 --- a/wgpu-types/src/math.rs +++ b/wgpu-types/src/math.rs @@ -1,31 +1,46 @@ //! Utility math functions. -use core::ops::{Add, Rem, Sub}; +/// Trait for adjusting integers to the next multiple of an alignment. +pub trait AlignTo: Copy { + /// Aligns `self` to `alignment`. + /// + /// Panics if doing so would overflow. + fn align_to(self, alignment: Self) -> Self; +} + +macro_rules! impl_align_to { + ($ty:ty) => { + impl AlignTo for $ty { + fn align_to(self, alignment: Self) -> Self { + self.checked_next_multiple_of(alignment).unwrap() + } + } + }; +} + +impl_align_to!(u32); +impl_align_to!(u64); +impl_align_to!(usize); -/// /// Aligns a `value` to an `alignment`. /// /// Returns the first number greater than or equal to `value` that is also a /// multiple of `alignment`. If `value` is already a multiple of `alignment`, /// `value` will be returned. /// +/// # Panics +/// +/// If aligning `value` to `alignment` would overflow. +/// /// # Examples /// /// ``` /// # use wgpu_types::math::align_to; -/// assert_eq!(align_to(253, 16), 256); -/// assert_eq!(align_to(256, 16), 256); -/// assert_eq!(align_to(0, 16), 0); +/// assert_eq!(align_to(253_u32, 16), 256); +/// assert_eq!(align_to(256_u32, 16), 256); +/// assert_eq!(align_to(0_u32, 16), 0); /// ``` /// -pub fn align_to(value: T, alignment: T) -> T -where - T: Add + Copy + Default + PartialEq + Rem + Sub, -{ - let remainder = value % alignment; - if remainder == T::default() { - value - } else { - value + alignment - remainder - } +pub fn align_to(value: T, alignment: T) -> T { + value.align_to(alignment) } diff --git a/wgpu-types/src/render.rs b/wgpu-types/src/render.rs index cbf8a7d89..2bef8e65b 100644 --- a/wgpu-types/src/render.rs +++ b/wgpu-types/src/render.rs @@ -470,7 +470,7 @@ pub enum IndexFormat { impl IndexFormat { /// Returns the size in bytes of the index format - pub fn byte_size(&self) -> usize { + pub fn byte_size(&self) -> u32 { match self { IndexFormat::Uint16 => 2, IndexFormat::Uint32 => 4,