Skip to content

Commit 8ad7ce5

Browse files
committed
add with_current_vm
1 parent b4b74a8 commit 8ad7ce5

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

vm/src/vm/thread.rs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,32 @@
11
use crate::{AsObject, PyObject, VirtualMachine};
22
use itertools::Itertools;
3-
use std::{cell::RefCell, ptr::NonNull, thread_local};
3+
use std::{
4+
cell::RefCell,
5+
ptr::{null, NonNull},
6+
thread_local,
7+
};
48

59
thread_local! {
610
pub(super) static VM_STACK: RefCell<Vec<NonNull<VirtualMachine>>> = Vec::with_capacity(1).into();
11+
static VM_CURRENT: RefCell<*const VirtualMachine> = null::<VirtualMachine>().into();
12+
}
13+
14+
pub fn with_current_vm<R>(f: impl FnOnce(&VirtualMachine) -> R) -> R {
15+
VM_CURRENT.with(|x| unsafe {
16+
f(x.clone()
17+
.into_inner()
18+
.as_ref()
19+
.expect("call with_current_vm() but VM_CURRENT is null"))
20+
})
721
}
822

923
pub fn enter_vm<R>(vm: &VirtualMachine, f: impl FnOnce() -> R) -> R {
1024
VM_STACK.with(|vms| {
1125
vms.borrow_mut().push(vm.into());
26+
let prev = VM_CURRENT.with(|current| current.replace(vm));
1227
let ret = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
1328
vms.borrow_mut().pop();
29+
VM_CURRENT.with(|current| current.replace(prev));
1430
ret.unwrap_or_else(|e| std::panic::resume_unwind(e))
1531
})
1632
}
@@ -35,7 +51,10 @@ where
3551
// SAFETY: all references in VM_STACK should be valid, and should not be changed or moved
3652
// at least until this function returns and the stack unwinds to an enter_vm() call
3753
let vm = unsafe { intp.as_ref() };
38-
Some(f(vm))
54+
let prev = VM_CURRENT.with(|current| current.replace(vm));
55+
let ret = f(vm);
56+
VM_CURRENT.with(|current| current.replace(prev));
57+
Some(ret)
3958
})
4059
}
4160

0 commit comments

Comments
 (0)