diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index 171ad1882..a1d7735f5 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -36,6 +36,7 @@ use crate::{ BufferMapPendingClosure, DeviceLostInvocation, HostMap, MissingDownlevelFlags, MissingFeatures, RenderPassContext, }, + error::ErrorSink, hal_label, init_tracker::{ BufferInitTracker, BufferInitTrackerAction, MemoryInitKind, TextureInitRange, @@ -284,6 +285,8 @@ pub struct Device { /// has been destroyed and its queues are empty. pub(crate) device_lost_closure: Mutex>, + pub(crate) error_sink: ErrorSink, + /// Stores the state of buffers and textures. pub(crate) trackers: Mutex, pub(crate) tracker_indices: TrackerIndexAllocators, @@ -654,6 +657,7 @@ impl Device { snatchable_lock: unsafe { SnatchLock::new(rank::DEVICE_SNATCHABLE_LOCK) }, valid: AtomicBool::new(true), device_lost_closure: Mutex::new(rank::DEVICE_LOST_CLOSURE, None), + error_sink: ErrorSink::new(), trackers: Mutex::new( rank::DEVICE_TRACKERS, DeviceTracker::new(ordered_buffer_usages, ordered_texture_usages), diff --git a/wgpu-core/src/error.rs b/wgpu-core/src/error.rs index 8c5eb8ab1..04e855763 100644 --- a/wgpu-core/src/error.rs +++ b/wgpu-core/src/error.rs @@ -1,12 +1,301 @@ +use alloc::string::ToString as _; use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; -use core::{error::Error, fmt}; +use core::fmt; use thiserror::Error; -#[cfg(send_sync)] -pub type ContextErrorSource = Box; -#[cfg(not(send_sync))] -pub type ContextErrorSource = Box; +use alloc::format; +use core::error; + +use hashbrown::HashMap; +use wgpu_sync::Mutex; +use wgt::error::{Error, ErrorFilter, ErrorSource, ErrorType, UncapturedErrorHandler, WebGpuError}; +use wgt::WasmNotSendSync; + +use crate::device::Device; + +/// Implementation of thread IDs for error scope tracking. +/// +/// Supports both std and no_std environments, though +/// the no_std implementation is a stub that does not +/// actually distinguish between threads. +pub mod thread_id { + #[cfg(feature = "std")] + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub struct ThreadId(std::thread::ThreadId); + + #[cfg(feature = "std")] + impl ThreadId { + pub fn current() -> Self { + ThreadId(std::thread::current().id()) + } + } + + #[cfg(not(feature = "std"))] + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub struct ThreadId(()); + + #[cfg(not(feature = "std"))] + impl ThreadId { + pub fn current() -> Self { + // A simple stub implementation for non-std environments. On + // no_std but multithreaded platforms, this will work, but + // make error scope global rather than thread-local. + ThreadId(()) + } + } +} + +pub struct ErrorScope { + pub error: Option, + pub filter: ErrorFilter, +} + +pub struct InternalErrorSink { + pub scopes: HashMap>, + uncaptured_handler: Option>, +} + +pub struct ErrorSink(pub Mutex); + +impl ErrorSink { + pub fn new() -> ErrorSink { + // The mutex is unranked as it's shortlived + ErrorSink(Mutex::new(InternalErrorSink::new())) + } + + #[cold] + #[track_caller] + #[inline(never)] + fn handle_error_inner( + &self, + error_type: ErrorType, + source: ErrorSource, + label: Option<&str>, + fn_ident: &'static str, + ) { + let source: ErrorSource = Box::new(ContextError { + fn_ident, + source, + label: label.unwrap_or_default().to_string(), + }); + let final_error_handling = { + let mut sink = self.0.lock(); + let error = match error_type { + ErrorType::Internal => { + let description = format_error(&*source); + Error::Internal { + source, + description, + } + } + ErrorType::OutOfMemory => Error::OutOfMemory { source }, + ErrorType::Validation => { + let description = format_error(&*source); + Error::Validation { + source, + description, + } + } + ErrorType::DeviceLost => return, // will be surfaced via callback + }; + sink.handle_error_or_return_handler(error) + }; + + if let Some(f) = final_error_handling { + // If the user has provided their own `uncaptured_handler` callback, invoke it now, + // having released our lock on `sink_mutex`. See the comments on + // `handle_error_or_return_handler` for details. + f(); + } + } + + #[inline] + #[track_caller] + pub fn handle_error( + &self, + source: impl WebGpuError + WasmNotSendSync + 'static, + label: Option<&str>, + fn_ident: &'static str, + ) { + let error_type = source.webgpu_error_type(); + self.handle_error_inner(error_type, Box::new(source), label, fn_ident) + } + + #[inline] + #[track_caller] + pub fn handle_error_nolabel( + &self, + source: impl WebGpuError + WasmNotSendSync + 'static, + fn_ident: &'static str, + ) { + let error_type = source.webgpu_error_type(); + self.handle_error_inner(error_type, Box::new(source), None, fn_ident) + } +} + +impl InternalErrorSink { + fn new() -> InternalErrorSink { + InternalErrorSink { + scopes: HashMap::new(), + uncaptured_handler: None, + } + } + + /// Deliver the error to + /// + /// * the innermost error scope, if any, or + /// * the uncaptured error handler, if there is one, or + /// * [`default_error_handler()`]. + /// + /// If a closure is returned, the caller should call it immediately after dropping the + /// [`ErrorSink`] mutex guard. This makes sure that the user callback is not called with + /// a wgpu mutex held. + #[track_caller] + #[must_use] + fn handle_error_or_return_handler(&mut self, err: Error) -> Option { + let filter = match err { + Error::OutOfMemory { .. } => ErrorFilter::OutOfMemory, + Error::Validation { .. } => ErrorFilter::Validation, + Error::Internal { .. } => ErrorFilter::Internal, + }; + let thread_id = thread_id::ThreadId::current(); + let scopes = self.scopes.entry(thread_id).or_default(); + match scopes.iter_mut().rev().find(|scope| scope.filter == filter) { + Some(scope) => { + if scope.error.is_none() { + scope.error = Some(err); + } + None + } + None => { + if let Some(custom_handler) = &self.uncaptured_handler { + let custom_handler = Arc::clone(custom_handler); + Some(move || (custom_handler)(err)) + } else { + // direct call preserves #[track_caller] where dyn can't + default_error_handler(err) + } + } + } + } +} + +impl fmt::Debug for InternalErrorSink { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ErrorSink") + } +} + +#[track_caller] +fn default_error_handler(err: Error) -> ! { + log::error!("Handling wgpu errors as fatal by default"); + panic!("wgpu error: {err}\n"); +} + +#[derive(Debug, Error)] +#[error("Error scope stack is empty")] +pub struct EmptyErrorScopeStack; + +impl Device { + pub fn on_uncaptured_error(&self, handler: Arc) { + let mut error_sink = self.error_sink.0.lock(); + error_sink.uncaptured_handler = Some(handler); + } + + /// + pub fn push_error_scope(&self, filter: ErrorFilter) { + let mut error_sink = self.error_sink.0.lock(); + let thread_id = thread_id::ThreadId::current(); + let scopes = error_sink.scopes.entry(thread_id).or_default(); + scopes.push(ErrorScope { + error: None, + filter, + }); + } + + /// + pub fn pop_error_scope(&self) -> Result, EmptyErrorScopeStack> { + // 1. If this is lost: + if !self.is_valid() { + // Resolve promise with null. + return Ok(None); + } + let mut error_sink = self.error_sink.0.lock(); + + let thread_id = thread_id::ThreadId::current(); + let scopes = error_sink.scopes.entry(thread_id).or_default(); + // 2. this.[[errorScopeStack]].size must be > 0. + match scopes.pop() { + // 3. Let scope be the result of popping an item off of this.[[errorScopeStack]]. + // 4. Let error be any one of the items in scope.[[errors]], or null if there are none. + Some(scope) => Ok(scope.error), + // otherwise Reject promise with an OperationError. + None => Err(EmptyErrorScopeStack), + } + } +} + +impl Device { + // wgpu manipulates the error sink directly + // to handle panicking + pub fn error_sink(&self) -> &ErrorSink { + &self.error_sink + } +} + +#[inline(never)] +pub fn format_error(err: &(dyn error::Error + 'static)) -> String { + let mut output = String::new(); + let mut level = 1; + + fn print_tree(output: &mut String, level: &mut usize, e: &(dyn error::Error + 'static)) { + let mut print = |e: &(dyn error::Error + 'static)| { + use core::fmt::Write; + writeln!(output, "{}{}", " ".repeat(*level * 2), e).unwrap(); + + if let Some(e) = e.source() { + *level += 1; + print_tree(output, level, e); + *level -= 1; + } + }; + if let Some(multi) = e.downcast_ref::() { + for e in multi.errors() { + print(e); + } + } else { + print(e); + } + } + + print_tree(&mut output, &mut level, err); + + format!("Validation Error\n\nCaused by:\n{output}") +} + +impl Device { + #[inline] + #[track_caller] + pub fn handle_error( + &self, + source: impl WebGpuError + WasmNotSendSync + 'static, + label: Option<&str>, + fn_ident: &'static str, + ) { + self.error_sink.handle_error(source, label, fn_ident); + } + + #[inline] + #[track_caller] + pub fn handle_error_nolabel( + &self, + source: impl WebGpuError + WasmNotSendSync + 'static, + fn_ident: &'static str, + ) { + self.error_sink.handle_error_nolabel(source, fn_ident); + } +} #[derive(Debug, Error)] #[error( @@ -18,18 +307,18 @@ pub type ContextErrorSource = Box; pub struct ContextError { pub fn_ident: &'static str, #[source] - pub source: ContextErrorSource, + pub source: ErrorSource, pub label: String, } /// Don't use this error type with thiserror's #[error(transparent)] #[derive(Clone)] pub struct MultiError { - inner: Vec>, + inner: Vec>, } impl MultiError { - pub fn new( + pub fn new( iter: impl ExactSizeIterator, ) -> Option { if iter.len() == 0 { @@ -40,7 +329,9 @@ impl MultiError { }) } - pub fn errors(&self) -> Box + '_> { + pub fn errors( + &self, + ) -> Box + '_> { Box::new(self.inner.iter().map(|e| e.as_ref())) } } @@ -57,8 +348,8 @@ impl fmt::Display for MultiError { } } -impl Error for MultiError { - fn source(&self) -> Option<&(dyn Error + 'static)> { +impl error::Error for MultiError { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { self.inner[0].source() } } diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index b5d3ac6e2..09e128e9f 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -2,7 +2,6 @@ use alloc::borrow::ToOwned; use alloc::{ borrow::Cow::{self, Borrowed}, boxed::Box, - format, string::{String, ToString as _}, sync::Arc, vec, @@ -21,12 +20,9 @@ use hashbrown::HashMap; use arrayvec::ArrayVec; use smallvec::SmallVec; -use wgc::{ - error::ContextErrorSource, pipeline::CreateShaderModuleError, - resource::BlasPrepareCompactResult, -}; +use wgc::{pipeline::CreateShaderModuleError, resource::BlasPrepareCompactResult}; use wgt::{ - error::{ErrorType, WebGpuError}, + error::{ErrorSource as ContextErrorSource, ErrorType, WebGpuError}, WasmNotSendSync, }; @@ -39,7 +35,7 @@ use crate::{ }; use crate::{dispatch::DispatchAdapter, util::Mutex}; -mod thread_id; +use wgc::error::{format_error, thread_id}; #[derive(Clone)] pub struct ContextWgpuCore(Arc); @@ -264,7 +260,7 @@ impl ContextWgpuCore { }); let final_error_handling = { let mut sink = sink_mutex.lock(); - let description = || self.format_error(&*source); + let description = || format_error(&*source); let error = match error_type { ErrorType::Internal => { let description = description(); @@ -326,37 +322,7 @@ impl ContextWgpuCore { cause: impl Error + WasmNotSendSync + 'static, operation: &'static str, ) -> ! { - panic!("Error in {operation}: {f}", f = self.format_error(&cause)); - } - - #[inline(never)] - fn format_error(&self, err: &(dyn Error + 'static)) -> String { - let mut output = String::new(); - let mut level = 1; - - fn print_tree(output: &mut String, level: &mut usize, e: &(dyn Error + 'static)) { - let mut print = |e: &(dyn Error + 'static)| { - use core::fmt::Write; - writeln!(output, "{}{}", " ".repeat(*level * 2), e).unwrap(); - - if let Some(e) = e.source() { - *level += 1; - print_tree(output, level, e); - *level -= 1; - } - }; - if let Some(multi) = e.downcast_ref::() { - for e in multi.errors() { - print(e); - } - } else { - print(e); - } - } - - print_tree(&mut output, &mut level, err); - - format!("Validation Error\n\nCaused by:\n{output}") + panic!("Error in {operation}: {f}", f = format_error(&cause)); } pub unsafe fn queue_as_hal( @@ -2202,7 +2168,7 @@ impl dispatch::BufferInterface for CoreBuffer { } .into() }) - .map_err(|err| crate::MapRangeError(self.context.format_error(&err))) + .map_err(|err| crate::MapRangeError(format_error(&err))) } fn unmap(&self) { diff --git a/wgpu/src/backend/wgpu_core/thread_id.rs b/wgpu/src/backend/wgpu_core/thread_id.rs deleted file mode 100644 index 10bc9ae81..000000000 --- a/wgpu/src/backend/wgpu_core/thread_id.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! Implementation of thread IDs for error scope tracking. -//! -//! Supports both std and no_std environments, though -//! the no_std implementation is a stub that does not -//! actually distinguish between threads. - -#[cfg(feature = "std")] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct ThreadId(std::thread::ThreadId); - -#[cfg(feature = "std")] -impl ThreadId { - pub fn current() -> Self { - ThreadId(std::thread::current().id()) - } -} - -#[cfg(not(feature = "std"))] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct ThreadId(()); - -#[cfg(not(feature = "std"))] -impl ThreadId { - pub fn current() -> Self { - // A simple stub implementation for non-std environments. On - // no_std but multithreaded platforms, this will work, but - // make error scope global rather than thread-local. - ThreadId(()) - } -}