Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
3906 lines (3592 loc) · 159 KB
/
Copy pathmod.rs
File metadata and controls
3906 lines (3592 loc) · 159 KB
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Implement virtual machine to run instructions.
//!
//! See also:
//! <https://github.com/ProgVal/pythonvm-rust/blob/master/src/processor/mod.rs>
#[cfg(feature = "rustpython-compiler")]
mod compile;
pub(crate) mod compile_mode;
#[cfg(feature = "rustpython-compiler")]
pub use compile::VmCompileError;
mod context;
pub mod crossinterp;
mod interpreter;
mod method;
#[cfg(feature = "rustpython-compiler")]
mod python_run;
pub mod runtime;
mod setting;
pub mod thread;
mod vm_new;
mod vm_object;
mod vm_ops;
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
builtins::{
self, PyBaseExceptionRef, PyBaseObject, PyDict, PyDictRef, PyFrozenSet, PyInt, PyList,
PyModule, PySet, PyStr, PyStrInterned, PyStrRef, PyTypeRef, PyUtf8Str, PyUtf8StrInterned,
PyWeak,
code::PyCode,
dict::{PyDictItems, PyDictKeys, PyDictValues},
pystr::AsPyStr,
tuple::PyTuple,
},
codecs::CodecsRegistry,
common::{hash::HashSecret, lock::PyMutex, rc::PyRc},
convert::ToPyObject,
exceptions::types::{PyBaseException, PyMemoryError},
frame::{ExecutionResult, FrameObject, FrameObjectRef},
frozen::FrozenModule,
function::{ArgMapping, FuncArgs, PySetterValue},
import,
protocol::{PyIterIter, PyIterReturn},
scope::Scope,
signal::{self, SignalHandlers},
stdlib,
types::{GetattroFunc, fn_addr},
warn::WarningsState,
};
use alloc::{borrow::Cow, collections::BTreeMap};
#[cfg(all(not(unix), feature = "threading"))]
use core::ptr::NonNull;
use core::{
cell::{Cell, OnceCell, RefCell},
sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering},
};
use crossbeam_utils::atomic::AtomicCell;
use std::{
collections::{HashMap, HashSet},
ffi::{OsStr, OsString},
};
pub use context::Context;
pub use interpreter::{Interpreter, InterpreterBuilder};
pub(crate) use method::PyMethod;
pub use runtime::{
InterpFeatureFlags, InterpreterConfig, InterpreterGil, InterpreterInfo, InterpreterWhence,
MAIN_INTERPRETER_ID,
};
pub use setting::{CheckHashPycsMode, Paths, PyConfig, Settings};
pub const MAX_MEMORY_SIZE: usize = isize::MAX as usize;
// Objects are live when they are on stack, or referenced by a name (for now)
/// Per-thread execution context for a single interpreter (≈ CPython `PyThreadState`).
///
/// A `VirtualMachine` holds thread-local eval state (exceptions, recursion, frames,
/// datastack) plus shared references to interpreter-owned data (`state`,
/// `builtins`, `sys_module`, `ctx`). Multiple VMs may share the same
/// [`PyGlobalState`] via `VirtualMachine::new_thread`; distinct interpreters
/// each have their own `PyGlobalState` (see [`Interpreter::create_subinterpreter`]).
///
/// To construct the main VM of an interpreter, use [`Interpreter`].
pub struct VirtualMachine {
pub builtins: PyRef<PyModule>,
pub sys_module: PyRef<PyModule>,
pub ctx: PyRc<Context>,
/// Thread-local data stack for bump-allocating frame-local data
/// (localsplus arrays for non-generator frames).
datastack: core::cell::UnsafeCell<crate::datastack::DataStack>,
pub wasm_id: Option<String>,
exceptions: RefCell<ExceptionStack>,
pub import_func: PyObjectRef,
pub(crate) importlib: PyObjectRef,
pub profile_func: RefCell<PyObjectRef>,
pub trace_func: RefCell<PyObjectRef>,
pub use_tracing: Cell<bool>,
/// Event currently being monitored, or -1 when not in a callback.
pub(crate) what_event: Cell<i32>,
tracing_depth: Cell<usize>,
pub recursion_limit: Cell<usize>,
pub(crate) signal_handlers: OnceCell<SignalHandlers>,
pub(crate) signal_rx: Option<signal::UserSignalReceiver>,
pub repr_guards: RefCell<HashSet<usize>>,
pub state: PyRc<PyGlobalState>,
pub initialized: bool,
recursion_depth: Cell<usize>,
/// Depth of native recursion that pushes no Python frame, counted only
/// where the stack pointer cannot be read. Everywhere else the native
/// stack itself answers, and nothing needs counting.
#[cfg(any(miri, target_env = "musl"))]
native_recursion_depth: Cell<usize>,
/// C stack soft limit for detecting stack overflow (like c_stack_soft_limit)
#[cfg_attr(any(miri, target_env = "musl"), allow(dead_code))]
c_stack_soft_limit: Cell<usize>,
/// Async generator firstiter hook (per-thread, set via sys.set_asyncgen_hooks)
pub async_gen_firstiter: RefCell<Option<PyObjectRef>>,
/// Async generator finalizer hook (per-thread, set via sys.set_asyncgen_hooks)
pub async_gen_finalizer: RefCell<Option<PyObjectRef>>,
/// Current running asyncio event loop for this thread
pub asyncio_running_loop: RefCell<Option<PyObjectRef>>,
/// Current running asyncio task for this thread
pub asyncio_running_task: RefCell<Option<PyObjectRef>>,
pub(crate) callable_cache: CallableCache,
pub(crate) audit_hooks: RefCell<Vec<PyObjectRef>>,
/// Side channel for TailCall: the bytecode loop stores the new frame
/// pointer here before returning `ExecutionResult::TailCall`.
/// Access only via `set_pending_tailcall` / `take_pending_tailcall`.
pending_tailcall_frame: Cell<Option<PendingFrame>>,
/// Owned reference that keeps callee raw pointers valid during TailCall.
/// Set by the exact-call handlers and moved into the trampoline's
/// `SuspendedFrame`. Uses UnsafeCell because the VM is per-thread and this
/// field is only accessed on the owning thread.
pending_tailcall_owner: core::cell::UnsafeCell<Option<PyObjectRef>>,
/// Side channel for GenResume, the counterpart of `pending_tailcall_*`:
/// the bytecode loop parks the generator to resume, the value to send it
/// and what to do with its outcome here before returning
/// `ExecutionResult::GenResume`.
pending_gen_resume: core::cell::UnsafeCell<Option<PendingGenResume>>,
/// Reusable backing store for the trampoline's suspended-frame stack.
/// Trampoline invocations nest strictly LIFO, so each one owns the region
/// above the length it found on entry and truncates back to it on the way
/// out; reusing one allocation keeps a trampoline entry free of malloc,
/// which matters because a generator body enters one per resume.
/// UnsafeCell because the VM is per-thread and no reference into the Vec
/// is held across anything that could push to it.
trampoline_stack: core::cell::UnsafeCell<Vec<SuspendedFrame>>,
}
/// Non-owning frame pointer for the non-unix threading frames stack.
/// The pointed-to frame is kept alive by the caller of with_frame/resume_gen_frame.
/// Unix threading builds publish the top frame through `ThreadSlot::top_frame`
/// and walk the rest via `FrameObject::previous`, so they do not use this type.
#[cfg(all(not(unix), feature = "threading"))]
#[derive(Copy, Clone)]
pub struct FramePtr(NonNull<Py<FrameObject>>);
#[cfg(all(not(unix), feature = "threading"))]
impl FramePtr {
/// # Safety
/// The pointed-to frame must still be alive.
#[must_use]
pub unsafe fn as_ref(&self) -> &Py<FrameObject> {
unsafe { self.0.as_ref() }
}
}
// SAFETY: FramePtr is only stored in a thread's shared frame stack
// (`ThreadSlot::frames`) while the corresponding FrameObjectRef is alive on that
// thread's call stack; readers dereference it under the slot mutex.
#[cfg(all(not(unix), feature = "threading"))]
unsafe impl Send for FramePtr {}
#[derive(Debug)]
struct ExceptionStack {
/// Linked list of handled-exception slots (`_PyErr_StackItem` chain).
/// Bottom element is the thread's base slot; generator/coroutine resume
/// pushes an additional slot. Normal frame calls do **not** push/pop.
stack: Vec<Option<PyBaseExceptionRef>>,
}
impl Default for ExceptionStack {
fn default() -> Self {
// Thread's base `_PyErr_StackItem` – always present.
Self { stack: vec![None] }
}
}
/// Stop-the-world state for fork safety. Before `fork()`, the requester
/// stops all other Python threads so they are not holding internal locks.
#[cfg(feature = "threading")]
pub struct StopTheWorldState {
/// Fast-path flag checked in the bytecode loop (like `_PY_EVAL_PLEASE_STOP_BIT`)
pub(crate) requested: AtomicBool,
/// Whether the world is currently stopped (`stw->world_stopped`).
world_stopped: AtomicBool,
/// Ident of the thread that requested the stop (like `stw->requester`)
requester: AtomicU64,
/// Single exclusion held for the whole stop→start span. Fork and GC are
/// both stop-the-world requesters driving this shared state; only one may
/// hold it at a time. Acquired before any stop bookkeeping (see
/// `acquire_exclusion`) and released by `start_the_world`/`reset_after_fork`.
exclusion: AtomicBool,
/// Signaled by suspending threads when their state transitions to SUSPENDED
notify_mutex: std::sync::Mutex<()>,
notify_cv: std::sync::Condvar,
/// Number of non-requester threads still expected to park for current stop request.
thread_countdown: AtomicI64,
/// Number of stop-the-world attempts.
stats_stop_calls: AtomicU64,
/// Most recent stop-the-world wait duration in ns.
stats_last_wait_ns: AtomicU64,
/// Total accumulated stop-the-world wait duration in ns.
stats_total_wait_ns: AtomicU64,
/// Max observed stop-the-world wait duration in ns.
stats_max_wait_ns: AtomicU64,
/// Number of poll-loop iterations spent waiting.
stats_poll_loops: AtomicU64,
/// Number of ATTACHED threads observed while polling.
stats_attached_seen: AtomicU64,
/// Number of DETACHED->SUSPENDED parks requested by requester.
stats_forced_parks: AtomicU64,
/// Number of suspend notifications from worker threads.
stats_suspend_notifications: AtomicU64,
/// Number of yield loops while attach waited on SUSPENDED->DETACHED.
stats_attach_wait_yields: AtomicU64,
/// Number of yield loops while suspend waited on SUSPENDED->DETACHED.
stats_suspend_wait_yields: AtomicU64,
}
#[cfg(feature = "threading")]
#[derive(Debug, Clone, Copy)]
pub struct StopTheWorldStats {
pub stop_calls: u64,
pub last_wait_ns: u64,
pub total_wait_ns: u64,
pub max_wait_ns: u64,
pub poll_loops: u64,
pub attached_seen: u64,
pub forced_parks: u64,
pub suspend_notifications: u64,
pub attach_wait_yields: u64,
pub suspend_wait_yields: u64,
pub world_stopped: bool,
}
#[cfg(feature = "threading")]
impl Default for StopTheWorldState {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "threading")]
impl StopTheWorldState {
#[must_use]
pub const fn new() -> Self {
Self {
requested: AtomicBool::new(false),
world_stopped: AtomicBool::new(false),
requester: AtomicU64::new(0),
exclusion: AtomicBool::new(false),
notify_mutex: std::sync::Mutex::new(()),
notify_cv: std::sync::Condvar::new(),
thread_countdown: AtomicI64::new(0),
stats_stop_calls: AtomicU64::new(0),
stats_last_wait_ns: AtomicU64::new(0),
stats_total_wait_ns: AtomicU64::new(0),
stats_max_wait_ns: AtomicU64::new(0),
stats_poll_loops: AtomicU64::new(0),
stats_attached_seen: AtomicU64::new(0),
stats_forced_parks: AtomicU64::new(0),
stats_suspend_notifications: AtomicU64::new(0),
stats_attach_wait_yields: AtomicU64::new(0),
stats_suspend_wait_yields: AtomicU64::new(0),
}
}
/// Wake the stop-the-world requester (called by each thread that suspends).
pub(crate) fn notify_suspended(&self) {
self.stats_suspend_notifications
.fetch_add(1, Ordering::Relaxed);
// Synchronize with requester wait loop to avoid lost wakeups.
let _guard = self.notify_mutex.lock().unwrap();
self.decrement_thread_countdown(1);
self.notify_cv.notify_one();
}
#[inline]
fn init_thread_countdown(&self, state: &PyGlobalState) -> i64 {
let requester = self.requester.load(Ordering::Relaxed);
let registry = state.thread_frames.lock();
// Keep requested/count initialization serialized with thread-slot
// registration (which also takes this lock), matching the
// HEAD_LOCK-guarded stop-the-world bookkeeping.
self.requested.store(true, Ordering::Release);
let count = registry
.iter()
.filter(|(thread_id, slot)| {
**thread_id != requester
&& slot.state.load(Ordering::Relaxed) != thread::THREAD_SHUTTING_DOWN
})
.count();
let count = (count.min(i64::MAX as usize)) as i64;
self.thread_countdown.store(count, Ordering::Release);
count
}
#[inline]
fn decrement_thread_countdown(&self, n: u64) {
if n == 0 {
return;
}
let n = (n.min(i64::MAX as u64)) as i64;
let prev = self.thread_countdown.fetch_sub(n, Ordering::AcqRel);
if prev <= n {
// Clamp at 0 for safety in case of duplicate notifications.
self.thread_countdown.store(0, Ordering::Release);
}
}
/// Try to CAS detached threads directly to SUSPENDED and check whether
/// stop countdown reached zero after parking detached threads.
fn park_detached_threads(&self, state: &PyGlobalState) -> bool {
use thread::{THREAD_ATTACHED, THREAD_DETACHED, THREAD_SHUTTING_DOWN, THREAD_SUSPENDED};
let requester = self.requester.load(Ordering::Relaxed);
let registry = state.thread_frames.lock();
let mut attached_seen = 0u64;
let mut forced_parks = 0u64;
#[expect(
clippy::iter_over_hash_type,
reason = "Iteration order doesn't matter here"
)]
for (&id, slot) in registry.iter() {
if id == requester {
continue;
}
let state = slot.state.load(Ordering::Relaxed);
if state == THREAD_DETACHED {
// CAS DETACHED → SUSPENDED (park without thread cooperation)
match slot.state.compare_exchange(
THREAD_DETACHED,
THREAD_SUSPENDED,
Ordering::AcqRel,
Ordering::Relaxed,
) {
Ok(_) => {
slot.stop_requested.store(false, Ordering::Release);
forced_parks = forced_parks.saturating_add(1);
}
Err(THREAD_ATTACHED) => {
// Set per-thread stop bit (_PY_EVAL_PLEASE_STOP_BIT).
slot.stop_requested.store(true, Ordering::Release);
crate::signal::set_stop_bit();
// Raced with a thread re-attaching; it will self-suspend.
attached_seen = attached_seen.saturating_add(1);
}
Err(THREAD_DETACHED) => {
// Extremely unlikely race; next poll will handle it.
}
Err(THREAD_SUSPENDED) => {
slot.stop_requested.store(false, Ordering::Release);
// Another path parked it first.
}
Err(THREAD_SHUTTING_DOWN) => {
slot.stop_requested.store(false, Ordering::Release);
}
Err(other) => {
debug_assert!(
false,
"unexpected thread state in park_detached_threads: {other}"
);
}
}
} else if state == THREAD_ATTACHED {
// Set per-thread stop bit (_PY_EVAL_PLEASE_STOP_BIT).
slot.stop_requested.store(true, Ordering::Release);
crate::signal::set_stop_bit();
// Thread is in bytecode — it will see `requested` and self-suspend
attached_seen = attached_seen.saturating_add(1);
}
// THREAD_SUSPENDED / THREAD_SHUTTING_DOWN → already parked
}
if attached_seen != 0 {
self.stats_attached_seen
.fetch_add(attached_seen, Ordering::Relaxed);
}
if forced_parks != 0 {
self.decrement_thread_countdown(forced_parks);
self.stats_forced_parks
.fetch_add(forced_parks, Ordering::Relaxed);
}
forced_parks != 0 && self.thread_countdown.load(Ordering::Acquire) == 0
}
/// Acquire the single stop-the-world exclusion in a park-friendly way.
///
/// Fork and GC both request stop-the-world through the same shared state;
/// without this exclusion their `requester`/`requested`/countdown words
/// could be clobbered by an interleaving requester, so the completion
/// check could never converge and a requester would wait on itself forever.
///
/// The acquire must be park-friendly. While another requester's stop is in
/// progress it sets this thread's stop bit and waits for it to suspend;
/// blocking on a plain lock here would keep this thread from ever reaching
/// that safepoint, so the active requester would wait for this thread while
/// this thread waits for the lock — a deadlock swap. Instead we poll and
/// honor the suspend request between tries. Suspending here is safe as long
/// as any lock a spinning requester still holds is never acquired
/// attached-blocking by another thread. The fork requester holds IMP_LOCK,
/// but its acquisition detaches (`allow_threads`), so no attached thread
/// blocks on it; the GC requester holds only the `collecting` mutex, which
/// is only ever `try_lock`'d. The active requester therefore force-parks
/// this thread, finishes its whole stop→start span, releases the exclusion,
/// and only then does this thread resume and acquire it.
fn acquire_exclusion(&self, state: &PyGlobalState) {
if self
.exclusion
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed)
.is_ok()
{
return;
}
loop {
crate::vm::thread::suspend_if_needed(state);
std::thread::yield_now();
if self
.exclusion
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed)
.is_ok()
{
return;
}
}
}
/// Release the stop-the-world exclusion taken by `acquire_exclusion`.
fn release_exclusion(&self) {
self.exclusion.store(false, Ordering::Release);
}
/// Stop all non-requester threads (`stop_the_world`).
///
/// 1. Sets `requested`, marking the requester thread.
/// 2. CAS detached threads to SUSPENDED.
/// 3. Waits (polling with 1 ms condvar timeout) for attached threads
/// to self-suspend in `check_signals`.
///
/// Takes the shared exclusion first so at most one requester (fork or GC)
/// drives the stop→start span at a time; it is released by
/// `start_the_world`/`reset_after_fork`.
pub fn stop_the_world(&self, state: &PyGlobalState) {
self.acquire_exclusion(state);
let start = std::time::Instant::now();
let requester_ident = crate::stdlib::_thread::get_ident();
self.requester.store(requester_ident, Ordering::Relaxed);
self.stats_stop_calls.fetch_add(1, Ordering::Relaxed);
let initial_countdown = self.init_thread_countdown(state);
stw_trace(format_args!("stop begin requester={requester_ident}"));
// Park detached threads and set stop bits, then confirm every other
// thread is SUSPENDED. The completion condition is level-triggered
// (`all_non_requester_suspended`) so an already-suspended thread that
// was counted but will not notify again cannot stall the stop.
self.park_detached_threads(state);
if initial_countdown == 0 || self.all_non_requester_suspended(state) {
self.world_stopped.store(true, Ordering::Release);
crate::common::lock::set_world_stopped(true);
#[cfg(debug_assertions)]
self.debug_assert_all_non_requester_suspended(state);
stw_trace(format_args!(
"stop end requester={requester_ident} wait_ns=0 polls=0"
));
return;
}
let mut polls = 0u64;
loop {
self.park_detached_threads(state);
if self.all_non_requester_suspended(state) {
break;
}
polls = polls.saturating_add(1);
// Wait up to 1 ms for a thread to notify us it suspended.
// Re-check under the wait mutex first to avoid a lost-wake race:
// a thread may have suspended and notified right before we enter wait.
let guard = self.notify_mutex.lock().unwrap();
if self.all_non_requester_suspended(state) {
drop(guard);
break;
}
let _ = self
.notify_cv
.wait_timeout(guard, core::time::Duration::from_millis(1));
}
if polls != 0 {
self.stats_poll_loops.fetch_add(polls, Ordering::Relaxed);
}
let wait_ns = start.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64;
self.stats_last_wait_ns.store(wait_ns, Ordering::Relaxed);
self.stats_total_wait_ns
.fetch_add(wait_ns, Ordering::Relaxed);
let mut prev_max = self.stats_max_wait_ns.load(Ordering::Relaxed);
while wait_ns > prev_max {
match self.stats_max_wait_ns.compare_exchange_weak(
prev_max,
wait_ns,
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => break,
Err(observed) => prev_max = observed,
}
}
self.world_stopped.store(true, Ordering::Release);
crate::common::lock::set_world_stopped(true);
#[cfg(debug_assertions)]
self.debug_assert_all_non_requester_suspended(state);
stw_trace(format_args!(
"stop end requester={requester_ident} wait_ns={wait_ns} polls={polls}"
));
}
/// Resume all suspended threads (`start_the_world`).
pub fn start_the_world(&self, state: &PyGlobalState) {
use thread::{THREAD_DETACHED, THREAD_SHUTTING_DOWN, THREAD_SUSPENDED};
let requester = self.requester.load(Ordering::Relaxed);
stw_trace(format_args!("start begin requester={requester}"));
let registry = state.thread_frames.lock();
// Clear the request flag BEFORE waking threads. Otherwise a thread
// returning from allow_threads → attach_thread could observe
// `requested == true`, re-suspend itself, and stay parked forever.
// Keep this write under the registry lock to serialize with new
// thread-slot initialization.
self.requested.store(false, Ordering::Release);
self.world_stopped.store(false, Ordering::Release);
crate::common::lock::set_world_stopped(false);
#[expect(
clippy::iter_over_hash_type,
reason = "Iteration order doesn't matter here"
)]
for (&id, slot) in registry.iter() {
if id == requester {
continue;
}
slot.stop_requested.store(false, Ordering::Release);
let state = slot.state.load(Ordering::Relaxed);
if state == THREAD_SHUTTING_DOWN {
// `_PyThreadState_RemoveExcept` + SetShuttingDown already
// took this thread off the resume path. Leave it hanging.
continue;
}
debug_assert!(
state == THREAD_SUSPENDED,
"non-requester thread not suspended at start-the-world: id={id} state={state}"
);
if state == THREAD_SUSPENDED {
slot.state.store(THREAD_DETACHED, Ordering::Release);
slot.thread.unpark();
}
}
drop(registry);
self.thread_countdown.store(0, Ordering::Release);
self.requester.store(0, Ordering::Relaxed);
// Drop the process-wide stop hint. Another interpreter may still
// have `stop_requested` threads; those keep parking via the
// per-thread check in `eval_breaker_tripped`.
crate::signal::clear_stop_bit();
#[cfg(debug_assertions)]
self.debug_assert_all_non_requester_detached(state);
// Release the exclusion last, ending the stop→start span so the next
// requester (fork or GC) can proceed.
self.release_exclusion();
stw_trace(format_args!("start end requester={requester}"));
}
/// Reset after fork in the child (only one thread alive).
pub fn reset_after_fork(&self) {
self.requested.store(false, Ordering::Relaxed);
self.world_stopped.store(false, Ordering::Relaxed);
crate::common::lock::set_world_stopped(false);
self.requester.store(0, Ordering::Relaxed);
self.thread_countdown.store(0, Ordering::Relaxed);
// Only one thread survives fork; any stop-the-world bit inherited
// from the parent is stale.
crate::signal::clear_stop_bit();
// The surviving child thread inherited the exclusion taken by the
// pre-fork `stop_the_world`; release it (no start_the_world runs here).
self.release_exclusion();
stw_trace(format_args!("reset-after-fork"));
}
#[inline]
pub(crate) fn requester_ident(&self) -> u64 {
self.requester.load(Ordering::Relaxed)
}
#[inline]
pub(crate) fn notify_thread_gone(&self) {
let _guard = self.notify_mutex.lock().unwrap();
self.decrement_thread_countdown(1);
self.notify_cv.notify_one();
}
pub fn stats_snapshot(&self) -> StopTheWorldStats {
StopTheWorldStats {
stop_calls: self.stats_stop_calls.load(Ordering::Relaxed),
last_wait_ns: self.stats_last_wait_ns.load(Ordering::Relaxed),
total_wait_ns: self.stats_total_wait_ns.load(Ordering::Relaxed),
max_wait_ns: self.stats_max_wait_ns.load(Ordering::Relaxed),
poll_loops: self.stats_poll_loops.load(Ordering::Relaxed),
attached_seen: self.stats_attached_seen.load(Ordering::Relaxed),
forced_parks: self.stats_forced_parks.load(Ordering::Relaxed),
suspend_notifications: self.stats_suspend_notifications.load(Ordering::Relaxed),
attach_wait_yields: self.stats_attach_wait_yields.load(Ordering::Relaxed),
suspend_wait_yields: self.stats_suspend_wait_yields.load(Ordering::Relaxed),
world_stopped: self.world_stopped.load(Ordering::Relaxed),
}
}
pub fn reset_stats(&self) {
self.stats_stop_calls.store(0, Ordering::Relaxed);
self.stats_last_wait_ns.store(0, Ordering::Relaxed);
self.stats_total_wait_ns.store(0, Ordering::Relaxed);
self.stats_max_wait_ns.store(0, Ordering::Relaxed);
self.stats_poll_loops.store(0, Ordering::Relaxed);
self.stats_attached_seen.store(0, Ordering::Relaxed);
self.stats_forced_parks.store(0, Ordering::Relaxed);
self.stats_suspend_notifications.store(0, Ordering::Relaxed);
self.stats_attach_wait_yields.store(0, Ordering::Relaxed);
self.stats_suspend_wait_yields.store(0, Ordering::Relaxed);
}
#[inline]
pub(crate) fn add_attach_wait_yields(&self, n: u64) {
if n != 0 {
self.stats_attach_wait_yields
.fetch_add(n, Ordering::Relaxed);
}
}
#[inline]
pub(crate) fn add_suspend_wait_yields(&self, n: u64) {
if n != 0 {
self.stats_suspend_wait_yields
.fetch_add(n, Ordering::Relaxed);
}
}
/// Whether every non-requester registered thread is currently SUSPENDED.
///
/// Level-triggered stop-the-world completion check. Relying on this rather
/// than solely on the edge-triggered `thread_countdown` avoids a
/// lost-decrement race under rapid back-to-back stops: a thread that is
/// already SUSPENDED when a new stop counts it neither notifies nor is
/// force-parked again, so an edge-based countdown could never reach zero.
fn all_non_requester_suspended(&self, state: &PyGlobalState) -> bool {
use thread::{THREAD_SHUTTING_DOWN, THREAD_SUSPENDED};
let requester = self.requester.load(Ordering::Relaxed);
let registry = state.thread_frames.lock();
#[expect(
clippy::iter_over_hash_type,
reason = "Iteration order doesn't matter here"
)]
for (&id, slot) in registry.iter() {
if id == requester {
continue;
}
let slot_state = slot.state.load(Ordering::Acquire);
if slot_state != THREAD_SUSPENDED && slot_state != THREAD_SHUTTING_DOWN {
return false;
}
}
true
}
#[cfg(debug_assertions)]
fn debug_assert_all_non_requester_suspended(&self, state: &PyGlobalState) {
use thread::{THREAD_SHUTTING_DOWN, THREAD_SUSPENDED};
let requester = self.requester.load(Ordering::Relaxed);
let registry = state.thread_frames.lock();
#[expect(
clippy::iter_over_hash_type,
reason = "Iteration order doesn't matter here"
)]
for (&id, slot) in registry.iter() {
if id == requester {
continue;
}
let state = slot.state.load(Ordering::Relaxed);
debug_assert!(
state == THREAD_SUSPENDED || state == THREAD_SHUTTING_DOWN,
"non-requester thread not suspended during stop-the-world: id={id} state={state}"
);
}
}
#[cfg(debug_assertions)]
fn debug_assert_all_non_requester_detached(&self, state: &PyGlobalState) {
use thread::THREAD_SUSPENDED;
let requester = self.requester.load(Ordering::Relaxed);
let registry = state.thread_frames.lock();
#[expect(
clippy::iter_over_hash_type,
reason = "Iteration order doesn't matter here"
)]
for (&id, slot) in registry.iter() {
if id == requester {
continue;
}
let state = slot.state.load(Ordering::Relaxed);
debug_assert!(
state != THREAD_SUSPENDED,
"non-requester thread still suspended after start-the-world: id={id} state={state}"
);
}
}
}
#[cfg(feature = "threading")]
pub(super) fn stw_trace_enabled() -> bool {
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ENABLED.get_or_init(|| crate::host_env::os::var_os("RUSTPYTHON_STW_TRACE").is_some())
}
#[cfg(feature = "threading")]
pub(super) fn stw_trace(msg: core::fmt::Arguments<'_>) {
if stw_trace_enabled() {
use core::fmt::Write as _;
// Avoid stdio locking here: this path runs around fork where a child
// may inherit a borrowed stderr lock and panic on eprintln!/stderr.
struct FixedBuf {
buf: [u8; 512],
len: usize,
}
impl core::fmt::Write for FixedBuf {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
if self.len >= self.buf.len() {
return Ok(());
}
let remain = self.buf.len() - self.len;
let src = s.as_bytes();
let n = src.len().min(remain);
self.buf[self.len..self.len + n].copy_from_slice(&src[..n]);
self.len += n;
Ok(())
}
}
let mut out = FixedBuf {
buf: [0u8; 512],
len: 0,
};
let _ = writeln!(
&mut out,
"[rp-stw tid={}] {}",
crate::stdlib::_thread::get_ident(),
msg
);
#[cfg(unix)]
crate::host_env::io::write_stderr_raw(&out.buf[..out.len]);
#[cfg(not(unix))]
{
use std::io::Write as _;
let _ = std::io::stderr().write_all(&out.buf[..out.len]);
}
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct CallableCache {
pub len: Option<PyObjectRef>,
pub isinstance: Option<PyObjectRef>,
pub list_append: Option<PyObjectRef>,
pub builtin_all: Option<PyObjectRef>,
pub builtin_any: Option<PyObjectRef>,
}
/// Per-interpreter shared state (≈ CPython `PyInterpreterState`).
///
/// Not process-global: each [`Interpreter`] (main or subinterpreter) owns its own
/// `PyGlobalState`. Process-wide pieces live elsewhere (`Context::genesis`,
/// GC, the interpreter registry in [`runtime`]).
pub struct PyGlobalState {
/// Unique process-global interpreter id (main is [`MAIN_INTERPRETER_ID`]).
pub interpreter_id: i64,
/// Top-level interpreter whose runtime owns this interpreter.
pub runtime_root_id: i64,
/// How this interpreter was created.
pub whence: runtime::InterpreterWhence,
/// True for every top-level (non-sub) interpreter, each of which keeps its
/// own signal and main-thread bookkeeping. Only the first one registered
/// becomes *the* process main — see [`runtime::main_interpreter_id`].
pub is_main: bool,
pub config: PyConfig,
pub module_defs: BTreeMap<&'static str, &'static builtins::PyModuleDef>,
pub frozen: HashMap<&'static str, FrozenModule, rapidhash::quality::RandomState>,
pub stacksize: AtomicCell<usize>,
pub thread_count: AtomicCell<usize>,
pub hash_secret: HashSecret,
/// Registered `atexit` callbacks, newest first. Shared ownership so
/// `atexit.unregister` can keep the entry it is comparing alive while the
/// list is unlocked, and still recognize it afterwards by identity.
pub atexit_funcs: PyMutex<Vec<PyRc<(PyObjectRef, FuncArgs)>>>,
pub codec_registry: CodecsRegistry,
pub finalizing: AtomicBool,
pub warnings: WarningsState,
pub override_frozen_modules: AtomicCell<isize>,
pub before_forkers: PyMutex<Vec<PyObjectRef>>,
pub after_forkers_child: PyMutex<Vec<PyObjectRef>>,
pub after_forkers_parent: PyMutex<Vec<PyObjectRef>>,
pub int_max_str_digits: AtomicCell<usize>,
pub switch_interval: AtomicCell<f64>,
/// Global trace function for all threads (set by sys._settraceallthreads)
pub global_trace_func: PyMutex<Option<PyObjectRef>>,
/// Global profile function for all threads (set by sys._setprofileallthreads)
pub global_profile_func: PyMutex<Option<PyObjectRef>>,
/// Global type mutation/versioning mutex for CPython-style FT type operations.
pub type_mutex: PyMutex<()>,
/// Main thread identifier (pthread_self on Unix)
#[cfg(feature = "threading")]
pub main_thread_ident: AtomicCell<u64>,
/// Registry of all threads' slots for sys._current_frames() and sys._current_exceptions()
#[cfg(feature = "threading")]
pub thread_frames: parking_lot::Mutex<HashMap<u64, stdlib::_thread::CurrentFrameSlot>>,
/// Registry of all ThreadHandles for fork cleanup
#[cfg(feature = "threading")]
pub thread_handles: parking_lot::Mutex<Vec<stdlib::_thread::HandleEntry>>,
/// Registry for non-daemon threads that need to be joined at shutdown
#[cfg(feature = "threading")]
pub shutdown_handles: parking_lot::Mutex<Vec<stdlib::_thread::ShutdownEntry>>,
/// sys.monitoring state (tool names, events, callbacks)
pub monitoring: PyMutex<stdlib::sys::monitoring::MonitoringState>,
/// Fast-path mask: OR of all tools' events. 0 means no monitoring overhead.
pub monitoring_events: stdlib::sys::monitoring::MonitoringEventsMask,
/// Incremented on every monitoring state change. Code objects compare their
/// local version against this to decide whether re-instrumentation is needed.
pub instrumentation_version: AtomicU64,
/// Stop-the-world state for pre-fork thread suspension
#[cfg(feature = "threading")]
pub stop_the_world: StopTheWorldState,
/// This interpreter's garbage collector policy and results.
pub gc: crate::gc_state::GcInterpreterState,
/// Isolated-interpreter feature flags (PEP 684 / PEP 734 config).
pub feature_flags: runtime::InterpFeatureFlags,
/// Whether the interpreter was configured with `gil="own"`.
pub own_gil: bool,
/// Whether `__main__` is currently executing via `_interpreters.exec` / `run_*`.
pub running_main: AtomicBool,
/// True after `initialize()` has finished (CPython "ready").
pub ready: AtomicBool,
/// Optional ID refcount used by `_interpreters.create(reqrefs=True)`.
pub id_refcount: AtomicI64,
/// When true, dropping the last ID ref destroys the interpreter.
pub require_idref: AtomicBool,
}
impl PyGlobalState {
#[inline]
#[must_use]
pub fn is_main_interpreter(&self) -> bool {
self.is_main
}
#[inline]
#[must_use]
pub fn allow_fork(&self) -> bool {
self.feature_flags.allow_fork
}
#[inline]
#[must_use]
pub fn allow_exec(&self) -> bool {
self.feature_flags.allow_exec
}
#[inline]
#[must_use]
pub fn allow_threads(&self) -> bool {
self.feature_flags.allow_threads
}
#[inline]
#[must_use]
pub fn allow_daemon_threads(&self) -> bool {
self.feature_flags.allow_daemon_threads
}
/// The config this interpreter was created with, rebuilt from the flags it
/// kept (`_PyInterpreterConfig_InitFromState`).
#[must_use]
pub fn config(&self) -> runtime::InterpreterConfig {
runtime::InterpreterConfig::from_state(self.feature_flags, self.own_gil)
}
}
pub fn process_hash_secret_seed() -> u32 {
use std::sync::OnceLock;
static SEED: OnceLock<u32> = OnceLock::new();
// os_random is expensive, but this is only ever called once
*SEED.get_or_init(|| u32::from_ne_bytes(rustpython_common::rand::os_random()))
}
/// A `NonNull<T>` wrapper that implements `Send + Sync`.
///
/// # Safety contract
///
/// This type bypasses Rust's `Send`/`Sync` bounds on `NonNull`. It is
/// sound **only** when the pointer is exclusively accessed by one thread
/// at a time. In this codebase, that invariant is upheld because
/// `VirtualMachine` is per-thread.
///
/// **Do not use this type outside `pending_tailcall_frame`.** It exists
/// solely to let a `Cell<Option<PendingFrame>>` field on the per-thread
/// VM satisfy `Send + Sync`. If you need a `Send`-able pointer
/// elsewhere, justify and document the safety invariant at that site.
#[repr(transparent)]
struct PendingFrame(core::ptr::NonNull<crate::frame::InterpreterFrame>);
impl Copy for PendingFrame {}
impl Clone for PendingFrame {
fn clone(&self) -> Self {
*self
}
}
// SAFETY: VirtualMachine is per-thread; the pointer is only ever
// accessed on the thread that wrote it. The pointed-to InterpreterFrame
// lives on that thread's datastack and is valid from set to take.
unsafe impl Send for PendingFrame {}
unsafe impl Sync for PendingFrame {}
/// Saved state from `gen_frame_link`, needed by `gen_frame_unlink` to
/// restore the previous frame chain and the frame's owner.
pub(crate) struct GenFrameLink {
old_chain: *const crate::frame::InterpreterFrame,
old_owner: i8,
}
/// Saved state from `enter_iframe`, needed by `exit_iframe` to restore
/// the previous frame chain and exception state.
pub(crate) struct IframeEntryState {
pub(crate) iframe_ptr: *const crate::frame::InterpreterFrame,
pub(crate) old_chain: *const crate::frame::InterpreterFrame,
pub(crate) saved_exc: Option<PyBaseExceptionRef>,
pub(crate) save_exc: bool,
}
/// A generator or coroutine the bytecode loop asked the trampoline to resume.
struct PendingGenResume {
/// The generator or coroutine object; an exact builtin one, neither
/// running nor closed when it was parked.
jen: PyObjectRef,
/// The value its `yield` produces.
value: PyObjectRef,
/// What the parking frame does with the outcome.
cont: crate::frame::GenCont,
}
/// Where a frame running under the trampoline came from, and therefore what
/// the trampoline owes it when it finishes.
///
/// The trampoline is entered with one frame already running — `Entry` or
/// `GenEntry` — and pushes one record per frame it enters itself.
enum FrameKind {
/// The frame `run_frame_fast` was called with. Its caller allocated the
/// data stack storage and releases it, but the `enter_iframe`
/// bookkeeping is the trampoline's to undo.
Entry(IframeEntryState),
/// The body of a generator or coroutine, entered from `run_gen_frame`.
/// `resume_gen_frame` already linked it into the frame chain and will
/// unlink it, so the trampoline touches neither the bookkeeping nor the
/// storage; a `Yield` out of it is the trampoline's own result.
GenEntry,
/// A data stack frame the trampoline itself entered for a `TailCall`.
Callee(IframeEntryState),
/// A generator or coroutine frame the trampoline itself resumed for a
/// `GenResume`.
Gen(crate::coroutine::FlatResume),
}
impl FrameKind {
/// What a frame of this kind may hand back to the trampoline.
#[inline]
const fn flatten(&self) -> crate::frame::Flatten {
match self {
Self::Entry(_) | Self::Callee(_) => crate::frame::Flatten::CallAndGenResume,
Self::GenEntry | Self::Gen(_) => crate::frame::Flatten::GenResume,