rustpython-vm 0.6.0

RustPython virtual machine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use core::{
    cell::{Cell, RefCell},
    fmt,
    ops::{Deref, DerefMut, Index, IndexMut, Range},
    sync::atomic::{AtomicBool, AtomicU8, Ordering},
};
use std::sync::mpsc;

#[cfg(windows)]
use core::sync::atomic::AtomicIsize;

use crate::{PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine};

pub(crate) const NSIG: usize = 64;

#[cfg(not(feature = "threading"))]
bitflagset::bitflag! {
    /// Eval-breaker bits checked once per bytecode instruction.
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    #[repr(u8)]
    enum EvalBreakerFlag {
        Signal = 0,
    }
}

#[cfg(feature = "threading")]
bitflagset::bitflag! {
    /// Eval-breaker bits checked once per bytecode instruction.
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    #[repr(u8)]
    enum EvalBreakerFlag {
        Signal = 0,
        Qsbr = 1,
        Stop = 3,
        Finalizing = 4,
    }
}

bitflagset::bitflagset! {
    #[derive(Copy, Clone, PartialEq, Eq)]
    struct EvalBreakerBits(u8): EvalBreakerFlag
}

bitflagset::atomic_bitflagset!(struct EvalBreaker(AtomicU8) on EvalBreakerBits);

/// Signal handlers and QSBR set bits with fetch_or (async-signal-safe,
/// lock-free); consumers clear only their own bit with fetch_and.
static EVAL_BREAKER: EvalBreaker = EvalBreaker::new();

#[expect(
    clippy::declare_interior_mutable_const,
    reason = "workaround for const array repeat limitation (rust issue #79270)"
)]
const ATOMIC_FALSE: AtomicBool = AtomicBool::new(false);

pub(crate) static TRIGGERS: [AtomicBool; NSIG] = [ATOMIC_FALSE; NSIG];

#[cfg(windows)]
static SIGINT_EVENT: AtomicIsize = AtomicIsize::new(0);

thread_local! {
    /// Prevent recursive signal handler invocation. When a Python signal
    /// handler is running, new signals are deferred until it completes.
    static IN_SIGNAL_HANDLER: Cell<bool> = const { Cell::new(false) };
}

struct SignalHandlerGuard;

impl Drop for SignalHandlerGuard {
    fn drop(&mut self) {
        IN_SIGNAL_HANDLER.with(|h| h.set(false));
    }
}

#[cfg_attr(feature = "flame-it", flame)]
#[inline(always)]
pub fn check_signals(vm: &VirtualMachine) -> PyResult<()> {
    if vm.signal_handlers.get().is_none() {
        return Ok(());
    }

    // Read-only check first: avoids cache-line invalidation on every
    // instruction when no signal is pending (the common case).
    if !EVAL_BREAKER.contains(&EvalBreakerFlag::Signal) {
        return Ok(());
    }

    // Atomic RMW only when a signal is actually pending.
    if !EVAL_BREAKER.remove(EvalBreakerFlag::Signal) {
        return Ok(());
    }

    trigger_signals(vm)
}

#[inline(never)]
#[cold]
fn trigger_signals(vm: &VirtualMachine) -> PyResult<()> {
    if IN_SIGNAL_HANDLER.with(|h| h.replace(true)) {
        // Already inside a signal handler — defer pending signals
        set_triggered();
        return Ok(());
    }
    let _guard = SignalHandlerGuard;

    let signal_handlers = vm
        .signal_handlers
        .get()
        .expect("should never fail since we check above");

    for (signum, trigger) in TRIGGERS.iter().enumerate().skip(1) {
        let triggered = trigger.swap(false, Ordering::Relaxed);
        if !triggered {
            continue;
        }

        // SAFETY: TRIGGERS has the same length as the signal_handlers
        let signum = unsafe { SignalNum::new_unchecked(signum as i32) };

        // Read the handler out and drop the borrow before running it. A
        // handler is free to call signal.signal(), which takes the same cell
        // mutably, and a live read borrow turns that into a panic.
        let handler = signal_handlers.borrow()[signum].clone();

        if let Some(handler) = handler
            && let Some(callable) = handler.to_callable()
        {
            callable.invoke((signum.as_i32(), vm.ctx.none()), vm)?;
        }
    }

    if let Some(signal_rx) = &vm.signal_rx {
        for f in signal_rx.rx.try_iter() {
            f(vm)?;
        }
    }

    Ok(())
}

pub(crate) fn set_triggered() {
    // fetch_or (not store) so a signal handler never clobbers the QSBR bit;
    // this compiles to a lock-free RMW, safe to call from a signal handler.
    EVAL_BREAKER.insert(EvalBreakerFlag::Signal);
}

/// Any eval-breaker bit pending? One relaxed load; checked per instruction.
#[inline(always)]
pub(crate) fn eval_breaker_pending() -> bool {
    !EVAL_BREAKER.is_empty()
}

/// Extra eval-breaker bits used only when more than one thread can run.
#[cfg(feature = "threading")]
mod mt {
    use super::{EVAL_BREAKER, EvalBreakerFlag};

    /// QSBR has retired allocations pending reclamation.
    pub(crate) fn set_qsbr_bit() {
        EVAL_BREAKER.insert(EvalBreakerFlag::Qsbr);
    }

    pub(crate) fn clear_qsbr_bit() {
        EVAL_BREAKER.remove(EvalBreakerFlag::Qsbr);
    }

    pub(crate) fn qsbr_bit_set() -> bool {
        EVAL_BREAKER.contains(&EvalBreakerFlag::Qsbr)
    }

    /// Record that some thread's `stop_requested` flag may be set. Shared by
    /// every thread rather than being per-thread: the fast path checked once
    /// per bytecode instruction becomes a single relaxed load of this word.
    /// Sticky until `start_the_world`/`reset_after_fork` clears it.
    pub(crate) fn set_stop_bit() {
        EVAL_BREAKER.insert(EvalBreakerFlag::Stop);
    }

    /// Clear the shared stop-the-world bit. Only safe to call from
    /// `start_the_world`/`reset_after_fork`.
    pub(crate) fn clear_stop_bit() {
        EVAL_BREAKER.remove(EvalBreakerFlag::Stop);
    }

    /// Record that finalization has begun (`Interpreter::finalize`). Set once
    /// and never cleared.
    pub(crate) fn set_finalizing_bit() {
        EVAL_BREAKER.insert(EvalBreakerFlag::Finalizing);
    }

    /// Drop every process-wide eval-breaker bit. Tests that assert a single
    /// thread's `stop_requested` must not trip `eval_breaker_pending` have to
    /// start from a clean word: cargo's Windows runner shares the process
    /// across `#[test]` functions, so a sibling can leave SIGNAL/QSBR/STOP.
    #[cfg(test)]
    pub(crate) fn clear_eval_breaker_for_test() {
        EVAL_BREAKER.clear();
    }
}

#[cfg(feature = "threading")]
pub(crate) use mt::{
    clear_qsbr_bit, clear_stop_bit, qsbr_bit_set, set_finalizing_bit, set_qsbr_bit, set_stop_bit,
};

#[cfg(all(test, feature = "threading"))]
pub(crate) use mt::clear_eval_breaker_for_test;

/// Reset all signal trigger state after fork in child process.
/// Stale triggers from the parent must not fire in the child.
#[cfg(all(unix, feature = "host_env"))]
pub(crate) fn clear_after_fork() {
    EVAL_BREAKER.remove(EvalBreakerFlag::Signal);
    for trigger in &TRIGGERS {
        trigger.store(false, Ordering::Relaxed);
    }
}

/// A valid signal number.
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct SignalNum(i32);

impl SignalNum {
    pub(crate) const VALID_RANGE: Range<i32> = 1..NSIG as i32;

    /// Alias for:
    /// ```rust
    /// # use rustpython_vm::signal::SignalNum;
    ///
    /// unsafe { SignalNum::new_unchecked(libc::SIGINT) };
    /// ```
    #[cfg(any(unix, windows))]
    #[allow(dead_code, reason = "Not used on all platforms")]
    pub(crate) const SIGINT: Self = Self(libc::SIGINT);

    /// Construct [`Self`] without any validation on the signalnum value.
    ///
    /// # Safety
    ///
    /// Caller's responsibility to ensure the signal num is valid.
    #[must_use]
    pub const unsafe fn new_unchecked(value: i32) -> Self {
        Self(value)
    }

    /// Get the self as an [`i32`].
    #[must_use]
    pub const fn as_i32(&self) -> i32 {
        self.0
    }

    /// Get the self as an [`usize`].
    #[must_use]
    pub const fn as_usize(&self) -> usize {
        self.0 as usize
    }
}

impl fmt::Display for SignalNum {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl From<SignalNum> for i32 {
    fn from(signalnum: SignalNum) -> Self {
        signalnum.as_i32()
    }
}

impl TryFrom<i32> for SignalNum {
    type Error = String;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        let bounds = cfg_select! {
            all(windows, feature = "host_env") => rustpython_host_env::signal::VALID_SIGNALS,
            _ => Self::VALID_RANGE,
        };

        if bounds.contains(&value) {
            Ok(Self(value))
        } else {
            Err("signal number out of range".into())
        }
    }
}

impl TryFromObject for SignalNum {
    fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
        Self::try_from(i32::try_from_borrowed_object(vm, &obj)?)
            .map_err(|msg| vm.new_value_error(msg))
    }
}

/// Similar to `PyErr_SetInterruptEx` in CPython
///
/// Missing signal handler for the given signal number is silently ignored.
#[cfg(all(not(target_arch = "wasm32"), feature = "host_env"))]
pub fn set_interrupt_ex(signum: SignalNum) -> PyResult<()> {
    use crate::stdlib::_signal::_signal::{SIG_DFL, SIG_IGN, run_signal};

    match signum.as_usize() {
        SIG_DFL | SIG_IGN => Ok(()),
        _ => {
            // interrupt the main thread with given signal number
            run_signal(signum.into());
            Ok(())
        }
    }
}

pub type UserSignal = Box<dyn FnOnce(&VirtualMachine) -> PyResult<()> + Send>;

#[derive(Clone, Debug)]
pub struct UserSignalSender {
    tx: mpsc::Sender<UserSignal>,
}

#[derive(Debug)]
pub struct UserSignalReceiver {
    rx: mpsc::Receiver<UserSignal>,
}

impl UserSignalSender {
    pub fn send(&self, sig: UserSignal) -> Result<(), UserSignalSendError> {
        self.tx
            .send(sig)
            .map_err(|mpsc::SendError(sig)| UserSignalSendError(sig))?;
        set_triggered();
        Ok(())
    }
}

pub struct UserSignalSendError(pub UserSignal);

impl fmt::Debug for UserSignalSendError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UserSignalSendError")
            .finish_non_exhaustive()
    }
}

impl fmt::Display for UserSignalSendError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("sending a signal to a exited vm")
    }
}

#[must_use]
pub fn user_signal_channel() -> (UserSignalSender, UserSignalReceiver) {
    let (tx, rx) = mpsc::channel();
    (UserSignalSender { tx }, UserSignalReceiver { rx })
}

#[cfg(windows)]
pub fn set_sigint_event(handle: isize) {
    SIGINT_EVENT.store(handle, Ordering::Release);
}

#[cfg(windows)]
pub fn get_sigint_event() -> Option<isize> {
    let handle = SIGINT_EVENT.load(Ordering::Acquire);
    if handle == 0 { None } else { Some(handle) }
}

pub struct SignalHandlersInner([Option<PyObjectRef>; NSIG]);

impl Default for SignalHandlersInner {
    fn default() -> Self {
        Self([const { None }; NSIG])
    }
}

impl Index<SignalNum> for SignalHandlersInner {
    type Output = Option<PyObjectRef>;

    fn index(&self, index: SignalNum) -> &Self::Output {
        &self.0[index.as_usize()]
    }
}

impl IndexMut<SignalNum> for SignalHandlersInner {
    fn index_mut(&mut self, index: SignalNum) -> &mut Self::Output {
        &mut self.0[index.as_usize()]
    }
}

pub struct SignalHandlers(Box<RefCell<SignalHandlersInner>>);

impl Default for SignalHandlers {
    fn default() -> Self {
        Self(Box::new(RefCell::new(SignalHandlersInner::default())))
    }
}

impl Deref for SignalHandlers {
    type Target = Box<RefCell<SignalHandlersInner>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for SignalHandlers {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}