Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
2322 lines (2107 loc) · 90.6 KB
/
Copy pathmod.rs
File metadata and controls
2322 lines (2107 loc) · 90.6 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;
mod context;
mod interpreter;
mod method;
#[cfg(feature = "rustpython-compiler")]
mod python_run;
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, PyDict, PyDictRef, PyInt, PyList, PyModule, 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,
frame::{ExecutionResult, Frame, FrameRef},
frozen::FrozenModule,
function::{ArgMapping, FuncArgs, PySetterValue},
import,
protocol::PyIterIter,
scope::Scope,
signal, stdlib,
warn::WarningsState,
};
use alloc::{borrow::Cow, collections::BTreeMap};
#[cfg(all(unix, feature = "threading"))]
use core::sync::atomic::AtomicI64;
use core::{
cell::{Cell, OnceCell, RefCell},
ptr::NonNull,
sync::atomic::{AtomicBool, 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 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)
/// Top level container of a python virtual machine. In theory you could
/// create more instances of this struct and have them operate fully isolated.
///
/// To construct this, please refer to the [`Interpreter`]
pub struct VirtualMachine {
pub builtins: PyRef<PyModule>,
pub sys_module: PyRef<PyModule>,
pub ctx: PyRc<Context>,
pub frames: RefCell<Vec<FramePtr>>,
/// 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>,
pub recursion_limit: Cell<usize>,
pub(crate) signal_handlers: OnceCell<Box<RefCell<[Option<PyObjectRef>; signal::NSIG]>>>,
pub(crate) signal_rx: Option<signal::UserSignalReceiver>,
pub repr_guards: RefCell<HashSet<usize>>,
pub state: PyRc<PyGlobalState>,
pub initialized: bool,
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>>,
}
/// Non-owning frame pointer for the frames stack.
/// The pointed-to frame is kept alive by the caller of with_frame/resume_gen_frame.
#[derive(Copy, Clone)]
pub struct FramePtr(NonNull<Py<Frame>>);
impl FramePtr {
/// # Safety
/// The pointed-to frame must still be alive.
#[must_use]
pub unsafe fn as_ref(&self) -> &Py<Frame> {
unsafe { self.0.as_ref() }
}
}
// SAFETY: FramePtr is only stored in the VM's frames Vec while the corresponding
// FrameRef is alive on the call stack. The Vec is always empty when the VM moves between threads.
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(all(unix, 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,
/// 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(all(unix, 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(all(unix, feature = "threading"))]
impl Default for StopTheWorldState {
fn default() -> Self {
Self::new()
}
}
#[cfg(all(unix, 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),
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, vm: &VirtualMachine) -> i64 {
let requester = self.requester.load(Ordering::Relaxed);
let registry = vm.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
.keys()
.filter(|&&thread_id| thread_id != requester)
.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, vm: &VirtualMachine) -> bool {
use thread::{THREAD_ATTACHED, THREAD_DETACHED, THREAD_SUSPENDED};
let requester = self.requester.load(Ordering::Relaxed);
let registry = vm.state.thread_frames.lock();
let mut attached_seen = 0u64;
let mut forced_parks = 0u64;
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);
// 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(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);
// Thread is in bytecode — it will see `requested` and self-suspend
attached_seen = attached_seen.saturating_add(1);
}
// THREAD_SUSPENDED → 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
}
/// 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`.
pub fn stop_the_world(&self, vm: &VirtualMachine) {
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(vm);
stw_trace(format_args!("stop begin requester={requester_ident}"));
if initial_countdown == 0 {
self.world_stopped.store(true, Ordering::Release);
#[cfg(debug_assertions)]
self.debug_assert_all_non_requester_suspended(vm);
stw_trace(format_args!(
"stop end requester={requester_ident} wait_ns=0 polls=0"
));
return;
}
let mut polls = 0u64;
loop {
if self.park_detached_threads(vm) {
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.thread_countdown.load(Ordering::Acquire) == 0 || self.park_detached_threads(vm)
{
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);
#[cfg(debug_assertions)]
self.debug_assert_all_non_requester_suspended(vm);
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, vm: &VirtualMachine) {
use thread::{THREAD_DETACHED, THREAD_SUSPENDED};
let requester = self.requester.load(Ordering::Relaxed);
stw_trace(format_args!("start begin requester={requester}"));
let registry = vm.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);
for (&id, slot) in registry.iter() {
if id == requester {
continue;
}
slot.stop_requested.store(false, Ordering::Release);
let state = slot.state.load(Ordering::Relaxed);
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);
#[cfg(debug_assertions)]
self.debug_assert_all_non_requester_detached(vm);
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);
self.requester.store(0, Ordering::Relaxed);
self.thread_countdown.store(0, Ordering::Relaxed);
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);
}
}
#[cfg(debug_assertions)]
fn debug_assert_all_non_requester_suspended(&self, vm: &VirtualMachine) {
use thread::THREAD_SUSPENDED;
let requester = self.requester.load(Ordering::Relaxed);
let registry = vm.state.thread_frames.lock();
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 not suspended during stop-the-world: id={id} state={state}"
);
}
}
#[cfg(debug_assertions)]
fn debug_assert_all_non_requester_detached(&self, vm: &VirtualMachine) {
use thread::THREAD_SUSPENDED;
let requester = self.requester.load(Ordering::Relaxed);
let registry = vm.state.thread_frames.lock();
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(all(unix, 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(all(unix, 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
);
crate::host_env::io::write_stderr_raw(&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>,
}
pub struct PyGlobalState {
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,
pub atexit_funcs: PyMutex<Vec<Box<(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>>,
/// 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(all(unix, feature = "threading"))]
pub stop_the_world: StopTheWorldState,
}
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()))
}
impl VirtualMachine {
fn init_callable_cache(&mut self) -> PyResult<()> {
self.callable_cache.len = Some(self.builtins.get_attr("len", self)?);
self.callable_cache.isinstance = Some(self.builtins.get_attr("isinstance", self)?);
let list_append = self
.ctx
.types
.list_type
.get_attr(self.ctx.intern_str("append"))
.ok_or_else(|| self.new_runtime_error("failed to cache list.append".to_owned()))?;
self.callable_cache.list_append = Some(list_append);
self.callable_cache.builtin_all = Some(self.builtins.get_attr("all", self)?);
self.callable_cache.builtin_any = Some(self.builtins.get_attr("any", self)?);
Ok(())
}
/// Bump-allocate `size` bytes from the thread data stack.
///
/// # Safety
/// The returned pointer must be freed by calling `datastack_pop` in LIFO order.
#[inline(always)]
pub(crate) fn datastack_push(&self, size: usize) -> *mut u8 {
unsafe { (*self.datastack.get()).push(size) }
}
/// Check whether the thread data stack currently has room for `size` bytes.
#[inline(always)]
pub(crate) fn datastack_has_space(&self, size: usize) -> bool {
unsafe { (*self.datastack.get()).has_space(size) }
}
/// Pop a previous data stack allocation.
///
/// # Safety
/// `base` must be a pointer returned by `datastack_push` on this VM,
/// and all allocations made after it must already have been popped.
#[inline(always)]
pub(crate) unsafe fn datastack_pop(&self, base: *mut u8) {
unsafe { (*self.datastack.get()).pop(base) }
}
/// Temporarily detach the current thread (ATTACHED → DETACHED) while
/// running `f`, then re-attach afterwards. Allows `stop_the_world` to
/// park this thread during blocking syscalls.
///
/// Equivalent to CPython's `Py_BEGIN_ALLOW_THREADS` / `Py_END_ALLOW_THREADS`.
#[inline]
pub fn allow_threads<R>(&self, f: impl FnOnce() -> R) -> R {
thread::allow_threads(self, f)
}
/// Check whether the current thread is the main thread.
/// Mirrors `_Py_ThreadCanHandleSignals`.
#[allow(dead_code)]
pub(crate) fn is_main_thread(&self) -> bool {
cfg_select! {
feature = "threading" => {
crate::stdlib::_thread::get_ident() == self.state.main_thread_ident.load()
}
_ => true,
}
}
/// Create a new `VirtualMachine` structure.
pub(crate) fn new(ctx: PyRc<Context>, state: PyRc<PyGlobalState>) -> Self {
flame_guard!("new VirtualMachine");
// make a new module without access to the vm; doesn't
// set __spec__, __loader__, etc. attributes
let new_module = |def| {
PyRef::new_ref(
PyModule::from_def(def),
ctx.types.module_type.to_owned(),
Some(ctx.new_dict()),
)
};
// Hard-core modules:
let builtins = new_module(stdlib::builtins::module_def(&ctx));
let sys_module = new_module(stdlib::sys::module_def(&ctx));
let import_func = ctx.none();
let importlib = ctx.none();
let profile_func = RefCell::new(ctx.none());
let trace_func = RefCell::new(ctx.none());
let signal_handlers = OnceCell::from(signal::new_signal_handlers());
let vm = Self {
builtins,
sys_module,
ctx,
frames: RefCell::new(vec![]),
datastack: core::cell::UnsafeCell::new(crate::datastack::DataStack::new()),
wasm_id: None,
exceptions: RefCell::default(),
import_func,
importlib,
profile_func,
trace_func,
use_tracing: Cell::new(false),
recursion_limit: Cell::new(if cfg!(debug_assertions) { 256 } else { 1000 }),
signal_handlers,
signal_rx: None,
repr_guards: RefCell::default(),
state,
initialized: false,
recursion_depth: Cell::new(0),
c_stack_soft_limit: Cell::new(Self::calculate_c_stack_soft_limit()),
async_gen_firstiter: RefCell::new(None),
async_gen_finalizer: RefCell::new(None),
asyncio_running_loop: RefCell::new(None),
asyncio_running_task: RefCell::new(None),
callable_cache: CallableCache::default(),
audit_hooks: RefCell::new(vec![]),
};
if vm.state.hash_secret.hash_str("")
!= vm
.ctx
.interned_str("")
.expect("empty str must be interned")
.hash(&vm)
{
panic!("Interpreters in same process must share the hash seed");
}
vm.builtins.init_dict(
vm.ctx.intern_str("builtins"),
Some(vm.ctx.intern_str(stdlib::builtins::DOC.unwrap()).to_owned()),
&vm,
);
vm.sys_module.init_dict(
vm.ctx.intern_str("sys"),
Some(vm.ctx.intern_str(stdlib::sys::DOC.unwrap()).to_owned()),
&vm,
);
// let name = vm.sys_module.get_attr("__name__", &vm).unwrap();
vm
}
/// set up the encodings search function
/// init_importlib must be called before this call
#[cfg(feature = "encodings")]
fn import_encodings(&mut self) -> PyResult<()> {
self.import("encodings", 0).map_err(|import_err| {
let rustpythonpath_env = crate::host_env::os::var("RUSTPYTHONPATH").ok();
let pythonpath_env = crate::host_env::os::var("PYTHONPATH").ok();
let env_set = rustpythonpath_env.as_ref().is_some() || pythonpath_env.as_ref().is_some();
let path_contains_env = self.state.config.paths.module_search_paths.iter().any(|s| {
Some(s.as_str()) == rustpythonpath_env.as_deref() || Some(s.as_str()) == pythonpath_env.as_deref()
});
let guide_message = if cfg!(feature = "freeze-stdlib") {
"`rustpython_pylib` may not be set while using `freeze-stdlib` feature. Try using `rustpython::InterpreterBuilder::init_stdlib` or manually call `builder.add_frozen_modules(rustpython_pylib::FROZEN_STDLIB)` in `rustpython_vm::Interpreter::builder()`."
} else if !env_set {
"Neither RUSTPYTHONPATH nor PYTHONPATH is set. Try setting one of them to the stdlib directory."
} else if path_contains_env {
"RUSTPYTHONPATH or PYTHONPATH is set, but it doesn't contain the encodings library. If you are customizing the RustPython vm/interpreter, try adding the stdlib directory to the path. If you are developing the RustPython interpreter, it might be a bug during development."
} else {
"RUSTPYTHONPATH or PYTHONPATH is set, but it wasn't loaded to `PyConfig::paths::module_search_paths`. If you are going to customize the RustPython vm/interpreter, those environment variables are not loaded in the Settings struct by default. Please try creating a customized instance of the Settings struct. If you are developing the RustPython interpreter, it might be a bug during development."
};
let mut msg = format!(
"RustPython could not import the encodings module. It usually means something went wrong. Please carefully read the following messages and follow the steps.\n\
\n\
{guide_message}");
if !cfg!(feature = "freeze-stdlib") {
msg += "\n\
If you don't have access to a consistent external environment (e.g. targeting wasm, embedding \
rustpython in another application), try enabling the `freeze-stdlib` feature.\n\
If this is intended and you want to exclude the encodings module from your interpreter, please remove the `encodings` feature from `rustpython-vm` crate.";
}
let err = self.new_runtime_error(msg);
err.set___cause__(Some(import_err));
err
})?;
Ok(())
}
fn import_ascii_utf8_encodings(&mut self) -> PyResult<()> {
// Use the Python import machinery (FrozenImporter) so modules get
// proper __spec__ and __loader__ attributes.
self.import("codecs", 0)?;
// Use dotted names when freeze-stdlib is enabled (modules come from Lib/encodings/),
// otherwise use underscored names (modules come from core_modules/).
let (ascii_module_name, utf8_module_name) = if cfg!(feature = "freeze-stdlib") {
("encodings.ascii", "encodings.utf_8")
} else {
("encodings_ascii", "encodings_utf_8")
};
// Register ascii encoding
// __import__("encodings.ascii") returns top-level "encodings", so
// look up the actual submodule in sys.modules.
self.import(ascii_module_name, 0)?;
let sys_modules = self.sys_module.get_attr(identifier!(self, modules), self)?;
let ascii_module = sys_modules.get_item(ascii_module_name, self)?;
let getregentry = ascii_module.get_attr("getregentry", self)?;
let codec_info = getregentry.call((), self)?;
self.state
.codec_registry
.register_manual("ascii", codec_info.try_into_value(self)?);
// Register utf-8 encoding (also as "utf8" alias since normalize_encoding_name
// maps "utf-8" → "utf_8" but leaves "utf8" as-is)
self.import(utf8_module_name, 0)?;
let utf8_module = sys_modules.get_item(utf8_module_name, self)?;
let getregentry = utf8_module.get_attr("getregentry", self)?;
let codec_info = getregentry.call((), self)?;
let utf8_codec: crate::codecs::PyCodec = codec_info.try_into_value(self)?;
self.state
.codec_registry
.register_manual("utf-8", utf8_codec.clone());
self.state
.codec_registry
.register_manual("utf8", utf8_codec);
// Register latin-1 / iso8859-1 aliases needed very early for stdio
// bootstrap (e.g. PYTHONIOENCODING=latin-1).
if cfg!(feature = "freeze-stdlib") {
self.import("encodings.latin_1", 0)?;
let latin1_module = sys_modules.get_item("encodings.latin_1", self)?;
let getregentry = latin1_module.get_attr("getregentry", self)?;
let codec_info = getregentry.call((), self)?;
let latin1_codec: crate::codecs::PyCodec = codec_info.try_into_value(self)?;
for name in ["latin-1", "latin_1", "latin1", "iso8859-1", "iso8859_1"] {
self.state
.codec_registry
.register_manual(name, latin1_codec.clone());
}
}
Ok(())
}
fn initialize(&mut self) {
flame_guard!("init VirtualMachine");
if self.initialized {
panic!("Double Initialize Error");
}
// Initialize main thread ident before any threading operations
#[cfg(feature = "threading")]
stdlib::_thread::init_main_thread_ident(self);
stdlib::builtins::init_module(self, &self.builtins);
let callable_cache_init = self.init_callable_cache();
self.expect_pyresult(callable_cache_init, "failed to initialize callable cache");
stdlib::sys::init_module(self, &self.sys_module, &self.builtins);
self.expect_pyresult(
stdlib::sys::set_bootstrap_stderr(self),
"failed to initialize bootstrap stderr",
);
let mut essential_init = || -> PyResult {
import::import_builtin(self, "_typing")?;
#[cfg(all(not(target_arch = "wasm32"), feature = "host_env"))]
import::import_builtin(self, "_signal")?;
#[cfg(any(feature = "parser", feature = "compiler"))]
import::import_builtin(self, "_ast")?;
#[cfg(not(feature = "threading"))]
import::import_frozen(self, "_thread")?;
let importlib = import::init_importlib_base(self)?;
self.import_ascii_utf8_encodings()?;
{
let io = import::import_builtin(self, "_io")?;
// Full stdio: FileIO → BufferedWriter → TextIOWrapper
#[cfg(all(feature = "host_env", feature = "stdio"))]
let make_stdio = |name: &str, fd: i32, write: bool| -> PyResult<PyObjectRef> {
let buffered_stdio = self.state.config.settings.buffered_stdio;
let unbuffered = write && !buffered_stdio;
let buf = crate::stdlib::_io::open(
self.ctx.new_int(fd).into(),
Some(if write { "wb" } else { "rb" }),
crate::stdlib::_io::OpenArgs {
buffering: if unbuffered { 0 } else { -1 },
closefd: false,
..Default::default()
},
self,
)?;
let raw = if unbuffered {
buf.clone()
} else {
buf.get_attr("raw", self)?
};
raw.set_attr("name", self.ctx.new_str(format!("<{name}>")), self)?;
let isatty = self.call_method(&raw, "isatty", ())?.is_true(self)?;
let write_through = !buffered_stdio;
let line_buffering = buffered_stdio && (isatty || fd == 2);
let newline = if cfg!(windows) { None } else { Some("\n") };
let encoding = self.state.config.settings.stdio_encoding.as_deref();
// stderr always uses backslashreplace (ignores stdio_errors)
let errors = if fd == 2 {
Some("backslashreplace")
} else {
self.state
.config
.settings
.stdio_errors
.as_deref()
.or_else(|| {
Some(if self.state.config.settings.stdio_encoding.is_some() {
"strict"
} else {
"surrogateescape"
})
})
};
let stdio = self.call_method(
&io,
"TextIOWrapper",
(
buf,
encoding,
errors,
newline,
line_buffering,
write_through,
),
)?;
let mode = if write { "w" } else { "r" };
stdio.set_attr("mode", self.ctx.new_str(mode), self)?;
Ok::<_, self::PyBaseExceptionRef>(stdio)
};
// Sandbox stdio: lightweight wrapper using Rust's std::io directly
#[cfg(all(not(feature = "host_env"), feature = "stdio"))]
let make_stdio = |name: &str, fd: i32, write: bool| {
let mode = if write { "w" } else { "r" };
let stdio = stdlib::sys::SandboxStdio {
fd,
name: format!("<{name}>"),
mode: mode.to_owned(),
}
.into_ref(&self.ctx);
Ok(stdio.into())
};
// No stdio: set to None (embedding use case)
#[cfg(not(feature = "stdio"))]
let make_stdio = |_name: &str, _fd: i32, _write: bool| {
Ok(crate::builtins::PyNone.into_pyobject(self))
};
let set_stdio = |name, fd, write| {
let stdio: PyObjectRef = make_stdio(name, fd, write)?;
let dunder_name = self.ctx.intern_str(format!("__{name}__"));
self.sys_module.set_attr(
dunder_name, // e.g. __stdin__
stdio.clone(),
self,
)?;
self.sys_module.set_attr(name, stdio, self)?;