Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
1757 lines (1585 loc) · 67.8 KB
/
Copy pathmod.rs
File metadata and controls
1757 lines (1585 loc) · 67.8 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};
use core::{
cell::{Cell, OnceCell, RefCell},
ptr::NonNull,
sync::atomic::{AtomicBool, AtomicU64, Ordering},
};
use crossbeam_utils::atomic::AtomicCell;
#[cfg(unix)]
use nix::{
sys::signal::{SaFlags, SigAction, SigSet, Signal::SIGINT, kill, sigaction},
unistd::getpid,
};
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>>,
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)
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>>,
}
/// Non-owning frame pointer for the frames stack.
/// The pointed-to frame is kept alive by the caller of with_frame_exc/resume_gen_frame.
#[derive(Copy, Clone)]
pub struct FramePtr(NonNull<Py<Frame>>);
impl FramePtr {
/// # Safety
/// The pointed-to frame must still be alive.
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, Default)]
struct ExceptionStack {
stack: Vec<Option<PyBaseExceptionRef>>,
}
pub struct PyGlobalState {
pub config: PyConfig,
pub module_defs: BTreeMap<&'static str, &'static builtins::PyModuleDef>,
pub frozen: HashMap<&'static str, FrozenModule, ahash::RandomState>,
pub stacksize: AtomicCell<usize>,
pub thread_count: AtomicCell<usize>,
pub hash_secret: HashSecret,
pub atexit_funcs: PyMutex<Vec<(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,
}
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 {
/// Check whether the current thread is the main thread.
/// Mirrors `_Py_ThreadCanHandleSignals`.
#[allow(dead_code)]
pub(crate) fn is_main_thread(&self) -> bool {
#[cfg(feature = "threading")]
{
crate::stdlib::thread::get_ident() == self.state.main_thread_ident.load()
}
#[cfg(not(feature = "threading"))]
{
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![]),
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),
};
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 = std::env::var("RUSTPYTHONPATH").ok();
let pythonpath_env = std::env::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);
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(
if self.state.config.settings.stdio_encoding.is_some() {
Some("strict")
} else {
Some("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)?;
Ok(())
};
set_stdio("stdin", 0, false)?;
set_stdio("stdout", 1, true)?;
set_stdio("stderr", 2, true)?;
let io_open = io.get_attr("open", self)?;
self.builtins.set_attr("open", io_open, self)?;
}
Ok(importlib)
};
let res = essential_init();
let importlib = self.expect_pyresult(res, "essential initialization failed");
#[cfg(feature = "host_env")]
if self.state.config.settings.allow_external_library
&& cfg!(feature = "rustpython-compiler")
&& let Err(e) = import::init_importlib_package(self, importlib)
{
eprintln!(
"importlib initialization failed. This is critical for many complicated packages."
);
self.print_exception(e);
}
#[cfg(not(feature = "host_env"))]
let _ = importlib;
let _expect_stdlib = cfg!(feature = "freeze-stdlib")
|| !self.state.config.paths.module_search_paths.is_empty();
#[cfg(feature = "encodings")]
if _expect_stdlib {
if let Err(e) = self.import_encodings() {
eprintln!(
"encodings initialization failed. Only utf-8 encoding will be supported."
);
self.print_exception(e);
}
} else {
// Here may not be the best place to give general `path_list` advice,
// but bare rustpython_vm::VirtualMachine users skipped proper settings must hit here while properly setup vm never enters here.
eprintln!(
"feature `encodings` is enabled but `paths.module_search_paths` is empty. \
Please add the library path to `settings.path_list`. If you intended to disable the entire standard library (including the `encodings` feature), please also make sure to disable the `encodings` feature.\n\
Tip: You may also want to add `\"\"` to `settings.path_list` in order to enable importing from the current working directory."
);
}
self.initialized = true;
}
/// Set the custom signal channel for the interpreter
pub fn set_user_signal_channel(&mut self, signal_rx: signal::UserSignalReceiver) {
self.signal_rx = Some(signal_rx);
}
/// Execute Python bytecode (`.pyc`) from an in-memory buffer.
///
/// When the RustPython CLI is available, `.pyc` files are normally executed by
/// invoking `rustpython <input>.pyc`. This method provides an alternative for
/// environments where the binary is unavailable or file I/O is restricted
/// (e.g. WASM).
///
/// ## Preparing a `.pyc` file
///
/// First, compile a Python source file into bytecode:
///
/// ```sh
/// # Generate a .pyc file
/// $ rustpython -m py_compile <input>.py
/// ```
///
/// ## Running the bytecode
///
/// Load the resulting `.pyc` file into memory and execute it using the VM:
///
/// ```no_run
/// use rustpython_vm::Interpreter;
/// Interpreter::without_stdlib(Default::default()).enter(|vm| {
/// let bytes = std::fs::read("__pycache__/<input>.rustpython-314.pyc").unwrap();
/// let main_scope = vm.new_scope_with_main().unwrap();
/// vm.run_pyc_bytes(&bytes, main_scope);
/// });
/// ```
pub fn run_pyc_bytes(&self, pyc_bytes: &[u8], scope: Scope) -> PyResult<()> {
let code = PyCode::from_pyc(pyc_bytes, Some("<pyc_bytes>"), None, None, self)?;
self.with_simple_run("<source>", |_module_dict| {
self.run_code_obj(code, scope)?;
Ok(())
})
}
pub fn run_code_obj(&self, code: PyRef<PyCode>, scope: Scope) -> PyResult {
use crate::builtins::{PyFunction, PyModule};
// Create a function object for module code, similar to CPython's PyEval_EvalCode
let func = PyFunction::new(code.clone(), scope.globals.clone(), self)?;
let func_obj = func.into_ref(&self.ctx).into();
// Extract builtins from globals["__builtins__"], like PyEval_EvalCode
let builtins = match scope
.globals
.get_item_opt(identifier!(self, __builtins__), self)?
{
Some(b) => {
if let Some(module) = b.downcast_ref::<PyModule>() {
module.dict().into()
} else {
b
}
}
None => self.builtins.dict().into(),
};
let frame =
Frame::new(code, scope, builtins, &[], Some(func_obj), self).into_ref(&self.ctx);
self.run_frame(frame)
}
#[cold]
pub fn run_unraisable(&self, e: PyBaseExceptionRef, msg: Option<String>, object: PyObjectRef) {
// During interpreter finalization, sys.unraisablehook may not be available,
// but we still need to report exceptions (especially from atexit callbacks).
// Write directly to stderr like PyErr_FormatUnraisable.
if self.state.finalizing.load(Ordering::Acquire) {
self.write_unraisable_to_stderr(&e, msg.as_deref(), &object);
return;
}
let sys_module = self.import("sys", 0).unwrap();
let unraisablehook = sys_module.get_attr("unraisablehook", self).unwrap();
let exc_type = e.class().to_owned();
let exc_traceback = e.__traceback__().to_pyobject(self); // TODO: actual traceback
let exc_value = e.into();
let args = stdlib::sys::UnraisableHookArgsData {
exc_type,
exc_value,
exc_traceback,
err_msg: self.new_pyobj(msg),
object,
};
if let Err(e) = unraisablehook.call((args,), self) {
println!("{}", e.as_object().repr(self).unwrap());
}
}
/// Write unraisable exception to stderr during finalization.
/// Similar to _PyErr_WriteUnraisableDefaultHook in CPython.
fn write_unraisable_to_stderr(
&self,
e: &PyBaseExceptionRef,
msg: Option<&str>,
object: &PyObjectRef,
) {
// Get stderr once and reuse it
let stderr = crate::stdlib::sys::get_stderr(self).ok();
let write_to_stderr = |s: &str, stderr: &Option<PyObjectRef>, vm: &VirtualMachine| {
if let Some(stderr) = stderr {
let _ = vm.call_method(stderr, "write", (s.to_owned(),));
} else {
eprint!("{}", s);
}
};
let msg_str = if let Some(msg) = msg {
format!("{msg}: ")
} else {
"Exception ignored in: ".to_owned()
};
write_to_stderr(&msg_str, &stderr, self);
let repr_result = object.repr(self);
let repr_wtf8 = repr_result
.as_ref()
.map_or("<object repr failed>".as_ref(), |s| s.as_wtf8());
write_to_stderr(&format!("{repr_wtf8}\n"), &stderr, self);
// Write exception type and message
let exc_type_name = e.class().name();
let msg = match e.as_object().str(self) {
Ok(exc_str) if !exc_str.as_wtf8().is_empty() => {
format!("{}: {}\n", exc_type_name, exc_str.as_wtf8())
}
_ => format!("{}\n", exc_type_name),
};
write_to_stderr(&msg, &stderr, self);
// Flush stderr to ensure output is visible
if let Some(ref stderr) = stderr {
let _ = self.call_method(stderr, "flush", ());
}
}
#[inline(always)]
pub fn run_frame(&self, frame: FrameRef) -> PyResult {
match self.with_frame(frame, |f| f.run(self))? {
ExecutionResult::Return(value) => Ok(value),
_ => panic!("Got unexpected result from function"),
}
}
/// Run `run` with main scope.
fn with_simple_run(
&self,
path: &str,
run: impl FnOnce(&Py<PyDict>) -> PyResult<()>,
) -> PyResult<()> {
let sys_modules = self.sys_module.get_attr(identifier!(self, modules), self)?;
let main_module = sys_modules.get_item(identifier!(self, __main__), self)?;
let module_dict = main_module.dict().expect("main module must have __dict__");
// Track whether we set __file__ (for cleanup)
let set_file_name = !module_dict.contains_key(identifier!(self, __file__), self);
if set_file_name {
module_dict.set_item(
identifier!(self, __file__),
self.ctx.new_str(path).into(),
self,
)?;
module_dict.set_item(identifier!(self, __cached__), self.ctx.none(), self)?;
}
let result = run(&module_dict);
self.flush_io();
// Cleanup __file__ and __cached__ after execution
if set_file_name {
let _ = module_dict.del_item(identifier!(self, __file__), self);
let _ = module_dict.del_item(identifier!(self, __cached__), self);
}
result
}
/// flush_io
///
/// Flush stdout and stderr. Errors are silently ignored.
fn flush_io(&self) {
if let Ok(stdout) = self.sys_module.get_attr("stdout", self) {
let _ = self.call_method(&stdout, identifier!(self, flush).as_str(), ());
}
if let Ok(stderr) = self.sys_module.get_attr("stderr", self) {
let _ = self.call_method(&stderr, identifier!(self, flush).as_str(), ());
}
}
/// Clear module references during shutdown.
/// Follows the same phased algorithm as pylifecycle.c finalize_modules():
/// no hardcoded module names, reverse import order, only builtins/sys last.
pub fn finalize_modules(&self) {
// Phase 1: Set special sys/builtins attributes to None, restore stdio
self.finalize_modules_delete_special();
// Phase 2: Remove all modules from sys.modules (set values to None),
// and collect weakrefs to modules preserving import order.
// No strong refs are kept — modules freed when their last ref drops.
let module_weakrefs = self.finalize_remove_modules();
// Phase 3: Clear sys.modules dict
self.finalize_clear_modules_dict();
// Phase 4: GC collect — modules removed from sys.modules are freed,
// exposing cycles (e.g., dict ↔ function.__globals__). GC collects
// these and calls __del__ while module dicts are still intact.
crate::gc_state::gc_state().collect_force(2);
// Phase 5: Clear module dicts in reverse import order using 2-pass algorithm.
// Skip builtins and sys — those are cleared last.
self.finalize_clear_module_dicts(&module_weakrefs);
// Phase 6: GC collect — pick up anything freed by dict clearing.
crate::gc_state::gc_state().collect_force(2);
// Phase 7: Clear sys and builtins dicts last
self.finalize_clear_sys_builtins_dict();
}
/// Phase 1: Set special sys attributes to None and restore stdio.
fn finalize_modules_delete_special(&self) {
let none = self.ctx.none();
let sys_dict = self.sys_module.dict();
// Set special sys attributes to None
for attr in &[
"path",
"argv",
"ps1",
"ps2",
"last_exc",
"last_type",
"last_value",
"last_traceback",
"path_importer_cache",
"meta_path",
"path_hooks",
] {
let _ = sys_dict.set_item(*attr, none.clone(), self);
}
// Restore stdin/stdout/stderr from __stdin__/__stdout__/__stderr__
for (std_name, dunder_name) in &[
("stdin", "__stdin__"),
("stdout", "__stdout__"),
("stderr", "__stderr__"),
] {
let restored = sys_dict
.get_item_opt(*dunder_name, self)
.ok()
.flatten()
.unwrap_or_else(|| none.clone());
let _ = sys_dict.set_item(*std_name, restored, self);
}
// builtins._ = None
let _ = self.builtins.dict().set_item("_", none, self);
}
/// Phase 2: Set all sys.modules values to None and collect weakrefs.
/// No strong refs are kept — modules are freed when removed from sys.modules
/// (if nothing else references them), allowing GC to collect their cycles.
fn finalize_remove_modules(&self) -> Vec<(String, PyRef<PyWeak>)> {
let mut module_weakrefs = Vec::new();
let Ok(modules) = self.sys_module.get_attr(identifier!(self, modules), self) else {
return module_weakrefs;
};
let Some(modules_dict) = modules.downcast_ref::<PyDict>() else {
return module_weakrefs;
};
let none = self.ctx.none();
let items: Vec<_> = modules_dict.into_iter().collect();
for (key, value) in items {
let name = key
.downcast_ref::<PyUtf8Str>()
.map(|s| s.as_str().to_owned())
.unwrap_or_default();
// Save weakref to module (for later dict clearing)
if value.downcast_ref::<PyModule>().is_some()
&& let Ok(weak) = value.downgrade(None, self)
{
module_weakrefs.push((name, weak));
}
// Set the value to None in sys.modules
let _ = modules_dict.set_item(&*key, none.clone(), self);
}
module_weakrefs
}
/// Phase 3: Clear sys.modules dict.
fn finalize_clear_modules_dict(&self) {
if let Ok(modules) = self.sys_module.get_attr(identifier!(self, modules), self)
&& let Some(modules_dict) = modules.downcast_ref::<PyDict>()
{
modules_dict.clear();
}
}
/// Phase 5: Clear module dicts in reverse import order.
/// Skip builtins and sys — those are cleared last in Phase 7.
fn finalize_clear_module_dicts(&self, module_weakrefs: &[(String, PyRef<PyWeak>)]) {
let builtins_dict = self.builtins.dict();
let sys_dict = self.sys_module.dict();
for (_name, weakref) in module_weakrefs.iter().rev() {
let Some(module_obj) = weakref.upgrade() else {
continue;
};
let Some(module) = module_obj.downcast_ref::<PyModule>() else {
continue;
};
let dict = module.dict();
// Skip builtins and sys — they are cleared last
if dict.is(&builtins_dict) || dict.is(&sys_dict) {
continue;
}
Self::module_clear_dict(&dict, self);
}
}
/// 2-pass module dict clearing (_PyModule_ClearDict algorithm).
/// Pass 1: Set names starting with '_' (except __builtins__) to None.
/// Pass 2: Set all remaining names (except __builtins__) to None.
pub(crate) fn module_clear_dict(dict: &Py<PyDict>, vm: &VirtualMachine) {
let none = vm.ctx.none();
// Pass 1: names starting with '_' (except __builtins__)
for (key, value) in dict.into_iter().collect::<Vec<_>>() {
if vm.is_none(&value) {
continue;
}
if let Some(key_str) = key.downcast_ref::<PyStr>() {
let name = key_str.as_wtf8();
if name.starts_with("_") && name != "__builtins__" {
let _ = dict.set_item(key_str, none.clone(), vm);
}
}
}
// Pass 2: all remaining (except __builtins__)
for (key, value) in dict.into_iter().collect::<Vec<_>>() {
if vm.is_none(&value) {
continue;
}
if let Some(key_str) = key.downcast_ref::<PyStr>()
&& key_str.as_bytes() != b"__builtins__"
{
let _ = dict.set_item(key_str.as_wtf8(), none.clone(), vm);
}
}
}
/// Phase 7: Clear sys and builtins dicts last.
fn finalize_clear_sys_builtins_dict(&self) {
Self::module_clear_dict(&self.sys_module.dict(), self);
Self::module_clear_dict(&self.builtins.dict(), self);
}
pub fn current_recursion_depth(&self) -> usize {
self.recursion_depth.get()
}
/// Stack margin bytes (like _PyOS_STACK_MARGIN_BYTES).
/// 2048 * sizeof(void*) = 16KB for 64-bit.
const STACK_MARGIN_BYTES: usize = 2048 * core::mem::size_of::<usize>();
/// Get the stack boundaries using platform-specific APIs.
/// Returns (base, top) where base is the lowest address and top is the highest.
#[cfg(all(not(miri), windows))]
fn get_stack_bounds() -> (usize, usize) {
use windows_sys::Win32::System::Threading::{
GetCurrentThreadStackLimits, SetThreadStackGuarantee,
};
let mut low: usize = 0;
let mut high: usize = 0;
unsafe {
GetCurrentThreadStackLimits(&mut low as *mut usize, &mut high as *mut usize);
// Add the guaranteed stack space (reserved for exception handling)
let mut guarantee: u32 = 0;
SetThreadStackGuarantee(&mut guarantee);
low += guarantee as usize;
}
(low, high)
}
/// Get stack boundaries on non-Windows platforms.
/// Falls back to estimating based on current stack pointer.
#[cfg(all(not(miri), not(windows)))]
fn get_stack_bounds() -> (usize, usize) {
// Use pthread_attr_getstack on platforms that support it
#[cfg(any(target_os = "linux", target_os = "android"))]
{
use libc::{
pthread_attr_destroy, pthread_attr_getstack, pthread_attr_t, pthread_getattr_np,
pthread_self,
};
let mut attr: pthread_attr_t = unsafe { core::mem::zeroed() };
unsafe {
if pthread_getattr_np(pthread_self(), &mut attr) == 0 {
let mut stack_addr: *mut libc::c_void = core::ptr::null_mut();
let mut stack_size: libc::size_t = 0;
if pthread_attr_getstack(&attr, &mut stack_addr, &mut stack_size) == 0 {
pthread_attr_destroy(&mut attr);
let base = stack_addr as usize;
let top = base + stack_size;
return (base, top);
}
pthread_attr_destroy(&mut attr);
}
}
}
#[cfg(target_os = "macos")]
{
use libc::{pthread_get_stackaddr_np, pthread_get_stacksize_np, pthread_self};
unsafe {
let thread = pthread_self();
let stack_top = pthread_get_stackaddr_np(thread) as usize;
let stack_size = pthread_get_stacksize_np(thread);
let stack_base = stack_top - stack_size;
return (stack_base, stack_top);
}
}
// Fallback: estimate based on current SP and a default stack size
#[allow(unreachable_code)]
{
let current_sp = psm::stack_pointer() as usize;
// Assume 8MB stack, estimate base
let estimated_size = 8 * 1024 * 1024;
let base = current_sp.saturating_sub(estimated_size);
let top = current_sp + 1024 * 1024; // Assume we're not at the very top
(base, top)
}
}
/// Calculate the C stack soft limit based on actual stack boundaries.
/// soft_limit = base + 2 * margin (for downward-growing stacks)
#[cfg(not(miri))]
fn calculate_c_stack_soft_limit() -> usize {
let (base, _top) = Self::get_stack_bounds();
// Soft limit is 2 margins above the base
base + Self::STACK_MARGIN_BYTES * 2
}
/// Miri doesn't support inline assembly, so disable C stack checking.
#[cfg(miri)]
fn calculate_c_stack_soft_limit() -> usize {
0
}
/// Check if we're near the C stack limit (like _Py_MakeRecCheck).
/// Returns true only when stack pointer is in the "danger zone" between