|
| 1 | +use super::VirtualMachine; |
| 2 | +use crate::{ |
| 3 | + AsObject, PyAtomicRef, PyObject, PyObjectRef, PyResult, |
| 4 | + builtins::{PyBaseException, PyType}, |
| 5 | + common::wtf8::Wtf8Buf, |
| 6 | +}; |
| 7 | +use core::cell::Cell; |
| 8 | + |
| 9 | +/// Owned by one execution context, like `PyThreadState.async_exc`. |
| 10 | +/// This is an external GC root, not an edge owned by a Python object. |
| 11 | +/// The VM is not Sync: only its owning execution thread accesses these flags. |
| 12 | +/// Cross-thread requests would require a separate synchronized API and wakeup. |
| 13 | +pub(super) struct PendingAsyncException { |
| 14 | + exception: PyAtomicRef<Option<PyObject>>, |
| 15 | + pending: Cell<bool>, |
| 16 | + closed: Cell<bool>, |
| 17 | +} |
| 18 | + |
| 19 | +impl Default for PendingAsyncException { |
| 20 | + fn default() -> Self { |
| 21 | + Self { |
| 22 | + exception: PyAtomicRef::new_empty(), |
| 23 | + pending: Cell::new(false), |
| 24 | + closed: Cell::new(false), |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +impl PendingAsyncException { |
| 30 | + pub(super) fn is_pending(&self) -> bool { |
| 31 | + self.pending.get() |
| 32 | + } |
| 33 | + |
| 34 | + pub(super) fn has_reference(&self) -> bool { |
| 35 | + !self.exception.load_ptr().is_null() |
| 36 | + } |
| 37 | + |
| 38 | + fn replace(&self, exception: Option<PyObjectRef>) -> Option<Option<PyObjectRef>> { |
| 39 | + if self.closed.get() { |
| 40 | + return None; |
| 41 | + } |
| 42 | + Some(self.exception.store(exception)) |
| 43 | + } |
| 44 | + |
| 45 | + fn notify(&self) { |
| 46 | + if !self.closed.get() { |
| 47 | + self.pending.set(true); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + fn take(&self) -> Option<PyObjectRef> { |
| 52 | + if !self.pending.replace(false) { |
| 53 | + return None; |
| 54 | + } |
| 55 | + self.exception.store(None) |
| 56 | + } |
| 57 | + |
| 58 | + fn close(&self) { |
| 59 | + // A cleared thread state cannot accept another request. Rejecting |
| 60 | + // reentrant requests makes this a single clear, not a finalizer drain. |
| 61 | + self.closed.set(true); |
| 62 | + self.pending.set(false); |
| 63 | + drop(self.exception.store(None)); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl VirtualMachine { |
| 68 | + /// Replace the currently attached thread state's asynchronous exception. |
| 69 | + /// The outer `None` means that this VM is inactive or is being cleared. |
| 70 | + /// The old owner is returned so callers can release it outside all locks, |
| 71 | + /// either before or after notification as required by their API contract. |
| 72 | + /// `None` as the input cancels; validation happens only during delivery. |
| 73 | + pub(crate) fn replace_async_exception( |
| 74 | + &self, |
| 75 | + exception: Option<PyObjectRef>, |
| 76 | + ) -> Option<Option<PyObjectRef>> { |
| 77 | + if !super::thread::try_with_current_vm(|vm| core::ptr::eq(vm, self)).unwrap_or(false) { |
| 78 | + return None; |
| 79 | + } |
| 80 | + self.async_exception.replace(exception) |
| 81 | + } |
| 82 | + |
| 83 | + pub(crate) fn notify_async_exception(&self) { |
| 84 | + self.async_exception.notify(); |
| 85 | + } |
| 86 | + |
| 87 | + /// Called only at bytecode safepoints, after pending signals and GC. |
| 88 | + pub(crate) fn raise_async_exception(&self) -> PyResult<()> { |
| 89 | + let Some(exception) = self.async_exception.take() else { |
| 90 | + return Ok(()); |
| 91 | + }; |
| 92 | + let class = match exception.downcast::<PyType>() { |
| 93 | + Ok(class) if class.fast_issubclass(self.ctx.exceptions.base_exception_type) => class, |
| 94 | + object => { |
| 95 | + let object: PyObjectRef = match object { |
| 96 | + Ok(class) => class.into(), |
| 97 | + Err(object) => object, |
| 98 | + }; |
| 99 | + let mut message = Wtf8Buf::from("_PyErr_SetObject: exception "); |
| 100 | + message.push_wtf8(object.repr(self)?.as_wtf8()); |
| 101 | + message.push_str(" is not a BaseException subclass"); |
| 102 | + return Err(self.new_system_error(message)); |
| 103 | + } |
| 104 | + }; |
| 105 | + |
| 106 | + // `_PyErr_SetNone` invokes the class through its metaclass, including |
| 107 | + // user __call__/__new__/__init__, rather than allocating a bare payload. |
| 108 | + let result = class.as_object().call((), self).and_then(|object| { |
| 109 | + object.downcast::<PyBaseException>().map_err(|object| { |
| 110 | + let mut message = Wtf8Buf::from("calling "); |
| 111 | + match class.as_object().repr(self) { |
| 112 | + Ok(repr) => message.push_wtf8(repr.as_wtf8()), |
| 113 | + Err(error) => return error, |
| 114 | + } |
| 115 | + message.push_str(" should have returned an instance of BaseException, not "); |
| 116 | + message.push_str(&object.class().slot_name()); |
| 117 | + self.new_type_error(message) |
| 118 | + }) |
| 119 | + }); |
| 120 | + let exception = match result { |
| 121 | + Ok(exception) => exception, |
| 122 | + Err(error) => { |
| 123 | + // CPython represents the NULL value passed by SetNone as |
| 124 | + // '<NULL>'; failure in repr's signal check uses '<unknown>'. |
| 125 | + #[cfg(not(target_arch = "wasm32"))] |
| 126 | + let args = if crate::signal::check_signals(self).is_ok() { |
| 127 | + "<NULL>" |
| 128 | + } else { |
| 129 | + "<unknown>" |
| 130 | + }; |
| 131 | + #[cfg(target_arch = "wasm32")] |
| 132 | + let args = "<NULL>"; |
| 133 | + let note = self.ctx.new_str(format!( |
| 134 | + "Normalization failed: type={} args={args}", |
| 135 | + class.slot_name() |
| 136 | + )); |
| 137 | + // A failed attempt to append the note must not replace the |
| 138 | + // exception raised by the class constructor. |
| 139 | + let _ = error.add_note(note, self); |
| 140 | + error |
| 141 | + } |
| 142 | + }; |
| 143 | + Err(exception) |
| 144 | + } |
| 145 | + |
| 146 | + /// Clear a thread-state root while its VM and frame slot are still usable. |
| 147 | + pub(crate) fn clear_async_exception(&self) { |
| 148 | + self.async_exception.close(); |
| 149 | + } |
| 150 | +} |
0 commit comments