From aaca95f2a34fd3c234c2b6079366964394f86fca Mon Sep 17 00:00:00 2001 From: Andy Leiserson Date: Wed, 2 Jul 2025 14:16:02 -0700 Subject: [PATCH] Restore unintentional support for zero-size buffers (cherry picked from commit c0a580d6f0343a725b3defa8be4fdf0a9691eaad) --- wgpu-core/src/binding_model.rs | 2 +- wgpu-core/src/command/bundle.rs | 31 ++++++--------- wgpu-core/src/command/render.rs | 19 +++++---- wgpu-core/src/command/render_command.rs | 21 +++++----- wgpu-core/src/device/resource.rs | 5 ++- wgpu-core/src/resource.rs | 51 +++++++++++++----------- wgpu-hal/examples/halmark/main.rs | 6 +-- wgpu-hal/src/dx12/command.rs | 4 +- wgpu-hal/src/dx12/device.rs | 2 +- wgpu-hal/src/dx12/mod.rs | 7 ---- wgpu-hal/src/gles/device.rs | 3 +- wgpu-hal/src/lib.rs | 53 ++++++++++++++++++------- wgpu-hal/src/metal/command.rs | 10 +++-- wgpu-hal/src/metal/device.rs | 7 +++- wgpu-hal/src/vulkan/device.rs | 4 +- wgpu-types/src/lib.rs | 6 +++ 16 files changed, 130 insertions(+), 101 deletions(-) diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index 621f2d70a..3b5dad1bd 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -88,7 +88,7 @@ pub enum BindingError { binding_size: u64, buffer_size: u64, }, - #[error("Buffer {buffer}: Binding offset {offset} is greater than or equal to buffer size {buffer_size}")] + #[error("Buffer {buffer}: Binding offset {offset} is greater than buffer size {buffer_size}")] BindingOffsetTooLarge { buffer: ResourceErrorIdent, offset: wgt::BufferAddress, diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index eb895c440..4359d1979 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -92,6 +92,8 @@ use core::{ use arrayvec::ArrayVec; use thiserror::Error; +use wgpu_hal::ShouldBeNonZeroExt; + use crate::{ binding_model::{BindError, BindGroup, PipelineLayout}, command::{ @@ -499,7 +501,7 @@ impl RenderBundleEncoder { buffer_id, index_format, offset, - size, + size: size.map(NonZeroU64::get), }); } } @@ -602,7 +604,7 @@ fn set_index_buffer( buffer_id: id::Id, index_format: wgt::IndexFormat, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderBundleErrorInner> { let buffer = buffer_guard.get(buffer_id).get()?; @@ -634,7 +636,7 @@ fn set_vertex_buffer( slot: u32, buffer_id: id::Id, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderBundleErrorInner> { let max_vertex_buffers = state.device.limits.max_vertex_buffers; if slot >= max_vertex_buffers { @@ -1150,11 +1152,8 @@ impl IndexState { .range .end .checked_sub(self.range.start) - .and_then(wgt::BufferSize::new); - assert!( - self.range.end <= self.buffer.size && binding_size.is_some(), - "index buffer range must have non-zero size and be contained in buffer", - ); + .filter(|_| self.range.end <= self.buffer.size) + .expect("index range must be contained in buffer"); if self.is_dirty { self.is_dirty = false; @@ -1162,7 +1161,7 @@ impl IndexState { buffer: self.buffer.clone(), index_format: self.format, offset: self.range.start, - size: binding_size, + size: Some(binding_size), }) } else { None @@ -1205,16 +1204,12 @@ impl VertexState { /// /// `slot` is the index of the vertex buffer slot that `self` tracks. fn flush(&mut self, slot: u32) -> Option { - // This was all checked before, but let's check again just in case. let binding_size = self .range .end .checked_sub(self.range.start) - .and_then(wgt::BufferSize::new); - assert!( - self.range.end <= self.buffer.size && binding_size.is_some(), - "vertex buffer range must have non-zero size and be contained in buffer", - ); + .filter(|_| self.range.end <= self.buffer.size) + .expect("vertex range must be contained in buffer"); if self.is_dirty { self.is_dirty = false; @@ -1222,7 +1217,7 @@ impl VertexState { slot, buffer: self.buffer.clone(), offset: self.range.start, - size: binding_size, + size: Some(binding_size), }) } else { None @@ -1571,7 +1566,7 @@ where pub mod bundle_ffi { use super::{RenderBundleEncoder, RenderCommand}; use crate::{id, RawString}; - use core::{convert::TryInto, slice}; + use core::{convert::TryInto, num::NonZeroU64, slice}; use wgt::{BufferAddress, BufferSize, DynamicOffset, IndexFormat}; /// # Safety @@ -1630,7 +1625,7 @@ pub mod bundle_ffi { slot, buffer_id, offset, - size, + size: size.map(NonZeroU64::get), }); } diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 48d51142f..87689b83d 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -1,11 +1,16 @@ use alloc::{borrow::Cow, sync::Arc, vec::Vec}; -use core::{fmt, num::NonZeroU32, str}; +use core::{ + fmt, + num::{NonZeroU32, NonZeroU64}, + str, +}; +use hal::ShouldBeNonZeroExt; use arrayvec::ArrayVec; use thiserror::Error; use wgt::{ - BufferAddress, BufferSize, BufferUsages, Color, DynamicOffset, IndexFormat, ShaderStages, - TextureSelector, TextureUsages, TextureViewDimension, VertexStepMode, + BufferAddress, BufferSize, BufferSizeOrZero, BufferUsages, Color, DynamicOffset, IndexFormat, + ShaderStages, TextureSelector, TextureUsages, TextureViewDimension, VertexStepMode, }; use crate::binding_model::BindGroup; @@ -2299,7 +2304,7 @@ fn set_index_buffer( buffer: Arc, index_format: IndexFormat, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderPassErrorInner> { api_log!("RenderPass::set_index_buffer {}", buffer.error_ident()); @@ -2339,7 +2344,7 @@ fn set_vertex_buffer( slot: u32, buffer: Arc, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderPassErrorInner> { api_log!( "RenderPass::set_vertex_buffer {slot} {}", @@ -3149,7 +3154,7 @@ impl Global { buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?, index_format, offset, - size, + size: size.map(NonZeroU64::get), }); Ok(()) @@ -3170,7 +3175,7 @@ impl Global { slot, buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?, offset, - size, + size: size.map(NonZeroU64::get), }); Ok(()) diff --git a/wgpu-core/src/command/render_command.rs b/wgpu-core/src/command/render_command.rs index 606d3fe94..f57ec026e 100644 --- a/wgpu-core/src/command/render_command.rs +++ b/wgpu-core/src/command/render_command.rs @@ -1,6 +1,6 @@ use alloc::sync::Arc; -use wgt::{BufferAddress, BufferSize, Color}; +use wgt::{BufferAddress, BufferSizeOrZero, Color}; use super::{Rect, RenderBundle}; use crate::{ @@ -24,13 +24,13 @@ pub enum RenderCommand { buffer_id: id::BufferId, index_format: wgt::IndexFormat, offset: BufferAddress, - size: Option, + size: Option, }, SetVertexBuffer { slot: u32, buffer_id: id::BufferId, offset: BufferAddress, - size: Option, + size: Option, }, SetBlendConstant(Color), SetStencilReference(u32), @@ -418,21 +418,18 @@ pub enum ArcRenderCommand { offset: BufferAddress, // For a render pass, this reflects the argument passed by the - // application, which may be `None`. For a render bundle, this reflects - // the validated size of the binding, and will be populated even in the - // case that the application omitted the size. - size: Option, + // application, which may be `None`. For a finished render bundle, this + // reflects the validated size of the binding, and will be populated + // even in the case that the application omitted the size. + size: Option, }, SetVertexBuffer { slot: u32, buffer: Arc, offset: BufferAddress, - // For a render pass, this reflects the argument passed by the - // application, which may be `None`. For a render bundle, this reflects - // the validated size of the binding, and will be populated even in the - // case that the application omitted the size. - size: Option, + // See comment in `SetIndexBuffer`. + size: Option, }, SetBlendConstant(Color), SetStencilReference(u32), diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index abfb20882..3d665536a 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -8,9 +8,10 @@ use alloc::{ use core::{ fmt, mem::{self, ManuallyDrop}, - num::NonZeroU32, + num::{NonZeroU32, NonZeroU64}, sync::atomic::{AtomicBool, Ordering}, }; +use hal::ShouldBeNonZeroExt; use arrayvec::ArrayVec; use bitflags::Flags; @@ -2182,7 +2183,7 @@ impl Device { buffer.check_usage(pub_usage)?; - let bb = buffer.binding(bb.offset, bb.size, snatch_guard)?; + let bb = buffer.binding(bb.offset, bb.size.map(NonZeroU64::get), snatch_guard)?; let bind_size = bb.size.get(); if bind_size > range_limit as u64 { diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index 3ab1b4d6f..504f6f371 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -439,35 +439,32 @@ impl Buffer { /// If `size` is `None`, then the remainder of the buffer starting from /// `offset` is used. /// - /// If the binding would overflow the buffer or is empty (see - /// [`hal::BufferBinding`]), then an error is returned. + /// If the binding would overflow the buffer, then an error is returned. + /// + /// Zero-size bindings are permitted here for historical reasons. Although + /// zero-size bindings are permitted by WebGPU, they are not permitted by + /// some backends. See [`Buffer::binding`] and + /// [#3170](https://github.com/gfx-rs/wgpu/issues/3170). pub fn resolve_binding_size( &self, offset: wgt::BufferAddress, - binding_size: Option, - ) -> Result { + binding_size: Option, + ) -> Result { let buffer_size = self.size; match binding_size { - Some(binding_size) => { - match offset.checked_add(binding_size.get()) { - // `binding_size` is not zero which means `end == buffer_size` is ok. - Some(end) if end <= buffer_size => Ok(binding_size), - _ => Err(BindingError::BindingRangeTooLarge { - buffer: self.error_ident(), - offset, - binding_size: binding_size.get(), - buffer_size, - }), - } - } + Some(binding_size) => match offset.checked_add(binding_size) { + Some(end) if end <= buffer_size => Ok(binding_size), + _ => Err(BindingError::BindingRangeTooLarge { + buffer: self.error_ident(), + offset, + binding_size, + buffer_size, + }), + }, None => { - // We require that `buffer_size - offset` converts to - // `BufferSize` (`NonZeroU64`) because bindings must not be - // empty. buffer_size .checked_sub(offset) - .and_then(wgt::BufferSize::new) .ok_or_else(|| BindingError::BindingOffsetTooLarge { buffer: self.error_ident(), offset, @@ -483,12 +480,20 @@ impl Buffer { /// If `size` is `None`, then the remainder of the buffer starting from /// `offset` is used. /// - /// If the binding would overflow the buffer or is empty (see - /// [`hal::BufferBinding`]), then an error is returned. + /// If the binding would overflow the buffer, then an error is returned. + /// + /// Zero-size bindings are permitted here for historical reasons. Although + /// zero-size bindings are permitted by WebGPU, they are not permitted by + /// some backends. Previous documentation for `hal::BufferBinding` + /// disallowed zero-size bindings, but this restriction was not honored + /// elsewhere in the code. Zero-size bindings need to be quashed or remapped + /// to a non-zero size, either universally in wgpu-core, or in specific + /// backends that do not support them. See + /// [#3170](https://github.com/gfx-rs/wgpu/issues/3170). pub fn binding<'a>( &'a self, offset: wgt::BufferAddress, - binding_size: Option, + binding_size: Option, snatch_guard: &'a SnatchGuard, ) -> Result, BindingError> { let buf_raw = self.try_raw(snatch_guard)?; diff --git a/wgpu-hal/examples/halmark/main.rs b/wgpu-hal/examples/halmark/main.rs index 5641eb4de..60eb3d59b 100644 --- a/wgpu-hal/examples/halmark/main.rs +++ b/wgpu-hal/examples/halmark/main.rs @@ -447,11 +447,7 @@ impl Example { let global_group = { let global_buffer_binding = unsafe { // SAFETY: This is the same size that was specified for buffer creation. - hal::BufferBinding::new_unchecked( - &global_buffer, - 0, - global_buffer_desc.size.try_into().unwrap(), - ) + hal::BufferBinding::new_unchecked(&global_buffer, 0, global_buffer_desc.size) }; let texture_binding = hal::TextureBinding { view: &texture_view, diff --git a/wgpu-hal/src/dx12/command.rs b/wgpu-hal/src/dx12/command.rs index f57e6b923..39e18af13 100644 --- a/wgpu-hal/src/dx12/command.rs +++ b/wgpu-hal/src/dx12/command.rs @@ -1136,7 +1136,7 @@ impl crate::CommandEncoder for super::CommandEncoder { ) { let ibv = Direct3D12::D3D12_INDEX_BUFFER_VIEW { BufferLocation: binding.resolve_address(), - SizeInBytes: binding.resolve_size() as u32, + SizeInBytes: binding.size.try_into().unwrap(), Format: auxil::dxgi::conv::map_index_format(format), }; @@ -1149,7 +1149,7 @@ impl crate::CommandEncoder for super::CommandEncoder { ) { let vb = &mut self.pass.vertex_buffers[index as usize]; vb.BufferLocation = binding.resolve_address(); - vb.SizeInBytes = binding.resolve_size() as u32; + vb.SizeInBytes = binding.size.try_into().unwrap(); self.pass.dirty_vertex_buffers |= 1 << index; } diff --git a/wgpu-hal/src/dx12/device.rs b/wgpu-hal/src/dx12/device.rs index 918dd5193..c6e0332e5 100644 --- a/wgpu-hal/src/dx12/device.rs +++ b/wgpu-hal/src/dx12/device.rs @@ -1417,7 +1417,7 @@ impl crate::Device for super::Device { let end = start + entry.count as usize; for data in &desc.buffers[start..end] { let gpu_address = data.resolve_address(); - let mut size = data.resolve_size() as u32; + let mut size = data.size.try_into().unwrap(); if has_dynamic_offset { match ty { diff --git a/wgpu-hal/src/dx12/mod.rs b/wgpu-hal/src/dx12/mod.rs index 2394533b7..965b755fe 100644 --- a/wgpu-hal/src/dx12/mod.rs +++ b/wgpu-hal/src/dx12/mod.rs @@ -854,13 +854,6 @@ unsafe impl Sync for Buffer {} impl crate::DynBuffer for Buffer {} impl crate::BufferBinding<'_, Buffer> { - fn resolve_size(&self) -> wgt::BufferAddress { - match self.size { - Some(size) => size.get(), - None => self.buffer.size - self.offset, - } - } - // TODO: Return GPU handle directly? fn resolve_address(&self) -> wgt::BufferAddress { (unsafe { self.buffer.resource.GetGPUVirtualAddress() }) + self.offset diff --git a/wgpu-hal/src/gles/device.rs b/wgpu-hal/src/gles/device.rs index da0486373..984859c89 100644 --- a/wgpu-hal/src/gles/device.rs +++ b/wgpu-hal/src/gles/device.rs @@ -1261,10 +1261,11 @@ impl crate::Device for super::Device { let binding = match layout.ty { wgt::BindingType::Buffer { .. } => { let bb = &desc.buffers[entry.resource_index as usize]; + assert!(bb.size != 0, "zero-size bindings are not supported"); super::RawBinding::Buffer { raw: bb.buffer.raw.unwrap(), offset: bb.offset.try_into().unwrap(), - size: bb.size.get().try_into().unwrap(), + size: bb.size.try_into().unwrap(), } } wgt::BindingType::Sampler { .. } => { diff --git a/wgpu-hal/src/lib.rs b/wgpu-hal/src/lib.rs index 5dae531a2..48e4cb00f 100644 --- a/wgpu-hal/src/lib.rs +++ b/wgpu-hal/src/lib.rs @@ -297,7 +297,7 @@ use core::{ borrow::Borrow, error::Error, fmt, - num::NonZeroU32, + num::{NonZeroU32, NonZeroU64}, ops::{Range, RangeInclusive}, ptr::NonNull, }; @@ -1964,7 +1964,7 @@ pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> { /// /// `wgpu_hal` guarantees that shaders compiled with /// [`ShaderModuleDescriptor::runtime_checks`] set to `true` cannot read or -/// write data via this binding outside the *accessible region* of [`buffer`]: +/// write data via this binding outside the *accessible region* of a buffer: /// /// - The accessible region starts at [`offset`]. /// @@ -1989,14 +1989,14 @@ pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> { /// Some back ends cannot tolerate zero-length regions; for example, see /// [VUID-VkDescriptorBufferInfo-offset-00340][340] and /// [VUID-VkDescriptorBufferInfo-range-00341][341], or the -/// documentation for GLES's [glBindBufferRange][bbr]. For this reason, a valid -/// `BufferBinding` must have `offset` strictly less than the size of the -/// buffer. +/// documentation for GLES's [glBindBufferRange][bbr]. This documentation +/// previously stated that a `BufferBinding` must have `offset` strictly less +/// than the size of the buffer, but this restriction was not honored elsewhere +/// in the code, so has been removed. However, it remains the case that +/// some backends do not support zero-length bindings, so additional +/// logic is needed somewhere to handle this properly. See +/// [#3170](https://github.com/gfx-rs/wgpu/issues/3170). /// -/// WebGPU allows zero-length bindings, and there is not currently a mechanism -/// in place -/// -/// [`buffer`]: BufferBinding::buffer /// [`offset`]: BufferBinding::offset /// [`size`]: BufferBinding::size /// [`Storage`]: wgt::BufferBindingType::Storage @@ -2016,12 +2016,11 @@ pub struct BufferBinding<'a, B: DynBuffer + ?Sized> { /// The offset at which the bound region starts. /// - /// Because zero-length bindings are not permitted (see above), this must be - /// strictly less than the size of the buffer. + /// This must be less or equal to the size of the buffer. pub offset: wgt::BufferAddress, /// The size of the region bound, in bytes. - pub size: wgt::BufferSize, + pub size: wgt::BufferSizeOrZero, } // We must implement this manually because `B` is not necessarily `Clone`. @@ -2035,6 +2034,25 @@ impl Clone for BufferBinding<'_, B> { } } +/// Temporary convenience trait to let us call `.get()` on `u64`s in code that +/// really wants to be using `NonZeroU64`. +/// TODO(): remove this +pub trait ShouldBeNonZeroExt { + fn get(&self) -> u64; +} + +impl ShouldBeNonZeroExt for NonZeroU64 { + fn get(&self) -> u64 { + NonZeroU64::get(*self) + } +} + +impl ShouldBeNonZeroExt for u64 { + fn get(&self) -> u64 { + *self + } +} + impl<'a, B: DynBuffer + ?Sized> BufferBinding<'a, B> { /// Construct a `BufferBinding` with the given contents. /// @@ -2047,15 +2065,20 @@ impl<'a, B: DynBuffer + ?Sized> BufferBinding<'a, B> { /// /// SAFETY: The caller is responsible for ensuring that a binding of `size` /// bytes starting at `offset` is contained within the buffer. - pub unsafe fn new_unchecked( + /// + /// The `S` type parameter is a temporary convenience to allow callers to + /// pass either a `u64` or a `NonZeroU64`. When the zero-size binding issue + /// is resolved, the argument should just match the type of the member. + /// TODO(): remove the parameter + pub unsafe fn new_unchecked>( buffer: &'a B, offset: wgt::BufferAddress, - size: wgt::BufferSize, + size: S, ) -> Self { Self { buffer, offset, - size, + size: size.into(), } } } diff --git a/wgpu-hal/src/metal/command.rs b/wgpu-hal/src/metal/command.rs index 4fc1987ce..9f331fd46 100644 --- a/wgpu-hal/src/metal/command.rs +++ b/wgpu-hal/src/metal/command.rs @@ -4,7 +4,7 @@ use alloc::{ borrow::{Cow, ToOwned as _}, vec::Vec, }; -use core::ops::Range; +use core::{num::NonZeroU64, ops::Range}; use metal::{ MTLIndexType, MTLLoadAction, MTLPrimitiveType, MTLScissorRect, MTLSize, MTLStoreAction, MTLViewport, MTLVisibilityResultMode, NSRange, @@ -977,9 +977,11 @@ impl crate::CommandEncoder for super::CommandEncoder { let encoder = self.state.render.as_ref().unwrap(); encoder.set_vertex_buffer(buffer_index, Some(&binding.buffer.raw), binding.offset); - self.state - .vertex_buffer_size_map - .insert(buffer_index, binding.size); + // https://github.com/gfx-rs/wgpu/issues/3170 + let size = + NonZeroU64::new(binding.size).expect("zero-size vertex buffers are not supported"); + + self.state.vertex_buffer_size_map.insert(buffer_index, size); if let Some((index, sizes)) = self .state diff --git a/wgpu-hal/src/metal/device.rs b/wgpu-hal/src/metal/device.rs index a3141194e..3653b2bc9 100644 --- a/wgpu-hal/src/metal/device.rs +++ b/wgpu-hal/src/metal/device.rs @@ -1,5 +1,5 @@ use alloc::{borrow::ToOwned as _, sync::Arc, vec::Vec}; -use core::{ptr::NonNull, sync::atomic}; +use core::{num::NonZeroU64, ptr::NonNull, sync::atomic}; use std::{thread, time}; use parking_lot::Mutex; @@ -928,9 +928,12 @@ impl crate::Device for super::Device { let end = start + 1; bg.buffers .extend(desc.buffers[start..end].iter().map(|source| { + // https://github.com/gfx-rs/wgpu/issues/3170 + let source_size = NonZeroU64::new(source.size) + .expect("zero-size bindings are not supported"); let binding_size = match ty { wgt::BufferBindingType::Storage { .. } => { - Some(source.size) + Some(source_size) } _ => None, }; diff --git a/wgpu-hal/src/vulkan/device.rs b/wgpu-hal/src/vulkan/device.rs index ea9cefa58..bbc9d7de2 100644 --- a/wgpu-hal/src/vulkan/device.rs +++ b/wgpu-hal/src/vulkan/device.rs @@ -1799,10 +1799,12 @@ impl crate::Device for super::Device { (buffer_infos, local_buffer_infos) = buffer_infos.extend(desc.buffers[start as usize..end as usize].iter().map( |binding| { + // https://github.com/gfx-rs/wgpu/issues/3170 + assert!(binding.size != 0, "zero-size bindings are not supported"); vk::DescriptorBufferInfo::default() .buffer(binding.buffer.raw) .offset(binding.offset) - .range(binding.size.get()) + .range(binding.size) }, )); write.buffer_info(local_buffer_infos) diff --git a/wgpu-types/src/lib.rs b/wgpu-types/src/lib.rs index 3ba3bbe26..cd79a26d8 100644 --- a/wgpu-types/src/lib.rs +++ b/wgpu-types/src/lib.rs @@ -60,6 +60,12 @@ pub type BufferAddress = u64; /// [`BufferSlice`]: ../wgpu/struct.BufferSlice.html pub type BufferSize = core::num::NonZeroU64; +/// Integral type used for buffer sizes that may be zero. +/// +/// Although the wgpu Rust API disallows zero-size `BufferSlice` and wgpu-hal +/// disallows zero-size bindings, WebGPU permits zero-size buffers and bindings. +pub type BufferSizeOrZero = u64; + /// Integral type used for binding locations in shaders. /// /// Used in [`VertexAttribute`]s and errors.