Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions crates/vm/src/vm/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2161,6 +2161,56 @@ for _ in range(40):
worker.join().expect("nested worker panicked");
}

#[cfg(feature = "threading")]
#[test]
fn nested_enter_restores_detached_state() {
use super::super::thread::{ThreadState, current_thread_slot};
use alloc::sync::Arc;
use core::panic::AssertUnwindSafe;
use std::panic::{catch_unwind, resume_unwind};

let main = Interpreter::without_stdlib(Default::default());
main.enter(|vm| {
let parent_slot = current_thread_slot().unwrap();
let sub = vm.allow_threads(|| {
let sub = main.create_subinterpreter();
assert_ne!(
parent_slot.state.load(Ordering::Acquire),
ThreadState::Attached as i32,
);
sub
});
for nested in [&main, &sub] {
for unwind in [false, true] {
vm.allow_threads(|| {
let result = catch_unwind(AssertUnwindSafe(|| {
nested.enter(|_| {
assert_eq!(
current_thread_slot().unwrap().state.load(Ordering::Acquire),
ThreadState::Attached as i32,
);
if unwind {
resume_unwind(Box::new(()));
}
});
}));
assert_eq!(result.is_err(), unwind);
assert!(Arc::ptr_eq(&current_thread_slot().unwrap(), &parent_slot));
// A concurrent collector may have suspended the detached slot.
assert_ne!(
parent_slot.state.load(Ordering::Acquire),
ThreadState::Attached as i32,
);
});
assert_eq!(
parent_slot.state.load(Ordering::Acquire),
ThreadState::Attached as i32,
);
}
}
});
}

/// A thread blocked on a detaching lock must not stall stop-the-world.
///
/// Blocking on a lock reaches no safepoint, so an interpreter thread that
Expand Down
62 changes: 40 additions & 22 deletions crates/vm/src/vm/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,14 +299,14 @@ fn set_current_vm<R>(vm: &VirtualMachine, f: impl FnOnce() -> R) -> R {
// Attach to this VM's interpreter, detaching the enclosing one if this is a
// switch between interpreters on the same OS thread.
#[cfg(feature = "threading")]
let switched = begin_interpreter_section(vm);
let section = begin_interpreter_section(vm);

VM_STACK.with(|vms| {
vms.borrow_mut().push(vm.into());
scopeguard::defer! {
vms.borrow_mut().pop();
#[cfg(feature = "threading")]
end_interpreter_section(switched);
end_interpreter_section(section);
}
f()
})
Expand Down Expand Up @@ -361,19 +361,19 @@ pub fn enter_vm<R>(vm: &VirtualMachine, f: impl FnOnce() -> R) -> R {
#[must_use]
pub(crate) struct VmBootstrapGuard {
#[cfg(feature = "threading")]
switched: bool,
section: InterpreterSection,
}

impl VmBootstrapGuard {
pub(crate) fn new(vm: &VirtualMachine) -> Self {
#[cfg(feature = "threading")]
let switched = begin_interpreter_section(vm);
let section = begin_interpreter_section(vm);

VM_STACK.with(|vms| vms.borrow_mut().push(vm.into()));

Self {
#[cfg(feature = "threading")]
switched,
section,
}
}
}
Expand All @@ -385,7 +385,7 @@ impl Drop for VmBootstrapGuard {
});

#[cfg(feature = "threading")]
end_interpreter_section(self.switched);
end_interpreter_section(self.section);
}
}

Expand All @@ -401,26 +401,31 @@ pub enum CurrentVmAttachState {
pub struct SavedThreadState {
vm_stack: Vec<NonNull<VirtualMachine>>,
gilstate_vm: Option<Box<ThreadedVirtualMachine>>,
was_attached: bool,
}

/// Detach the current native thread and preserve its VM context for restoration.
#[cfg(feature = "threading")]
#[must_use = "the saved thread state must be restored"]
pub fn save_current_thread() -> SavedThreadState {
let was_attached = current_slot_is_attached();
let vm_stack = VM_STACK.with(|vms| core::mem::take(&mut *vms.borrow_mut()));
assert!(
!vm_stack.is_empty(),
"save_current_thread() called without an attached VM"
);
let gilstate_vm = GILSTATE_VM.with(|gilstate_vm| gilstate_vm.borrow_mut().take());
detach_thread();
if was_attached {
detach_thread();
}
SavedThreadState {
vm_stack,
gilstate_vm,
was_attached,
}
}

/// Restore a VM context previously returned by [`save_current_thread`].
/// Restore the VM context and attachment state returned by [`save_current_thread`].
#[cfg(feature = "threading")]
pub fn restore_current_thread(state: SavedThreadState) {
assert!(
Expand All @@ -430,6 +435,7 @@ pub fn restore_current_thread(state: SavedThreadState) {
let SavedThreadState {
vm_stack,
gilstate_vm,
was_attached,
} = state;
let vm = vm_stack
.last()
Expand All @@ -453,7 +459,9 @@ pub fn restore_current_thread(state: SavedThreadState) {
// subinterpreter slot (DETACHED); attaching that would leave the parent
// slot detached and later confuse outermost detach.
init_thread_slot_if_needed(vm);
attach_thread(vm);
if was_attached {
attach_thread(vm);
}
VM_STACK.with(|vms| *vms.borrow_mut() = vm_stack);
}

Expand Down Expand Up @@ -625,6 +633,13 @@ fn current_slot_is_attached() -> bool {
})
}

#[cfg(feature = "threading")]
#[derive(Clone, Copy)]
enum InterpreterSection {
Unchanged,
Switched { was_attached: bool },
}

/// Attach this thread to `vm`'s interpreter for the duration of a section,
/// detaching whichever interpreter it was attached to (≈ `_PyThreadState_Swap`).
///
Expand All @@ -634,35 +649,36 @@ fn current_slot_is_attached() -> bool {
/// code while B's slot is DETACHED would let a collector conclude B is stopped
/// while this thread keeps mutating the (process-global) object graph.
///
/// Returns whether the attachment changed, i.e. whether the matching
/// [`end_interpreter_section`] must undo it.
/// Preserve the enclosing attachment state for [`end_interpreter_section`],
/// including a detached `allow_threads` scope.
#[cfg(feature = "threading")]
fn begin_interpreter_section(vm: &VirtualMachine) -> bool {
fn begin_interpreter_section(vm: &VirtualMachine) -> InterpreterSection {
let target = ensure_thread_slot(vm);
let was_attached = current_slot_is_attached();
let already_current = CURRENT_THREAD_SLOT.with(|slot| {
slot.borrow()
.as_ref()
.is_some_and(|s| Arc::ptr_eq(s, &target))
});
if already_current && current_slot_is_attached() {
if already_current && was_attached {
// Nested section in the same interpreter: already attached.
return false;
return InterpreterSection::Unchanged;
}
if !already_current && current_slot_is_attached() {
if was_attached {
detach_thread();
}
set_current_thread_slot(target);
attach_thread(vm);
true
InterpreterSection::Switched { was_attached }
}

/// Undo [`begin_interpreter_section`]: detach this interpreter and re-attach the
/// enclosing one, if any. Call after the VM has been popped from `VM_STACK`.
/// Undo [`begin_interpreter_section`]: detach this interpreter and restore the
/// enclosing one's attachment state. Call after the VM is popped from `VM_STACK`.
#[cfg(feature = "threading")]
fn end_interpreter_section(switched: bool) {
if !switched {
fn end_interpreter_section(section: InterpreterSection) {
let InterpreterSection::Switched { was_attached } = section else {
return;
}
};
if current_slot_is_attached() {
detach_thread();
}
Expand All @@ -671,7 +687,9 @@ fn end_interpreter_section(switched: bool) {
// SAFETY: entries on VM_STACK are valid for their enter/set_current_vm scope.
let vm = unsafe { vm_ptr.as_ref() };
set_current_thread_slot(ensure_thread_slot(vm));
attach_thread(vm);
if was_attached {
attach_thread(vm);
}
}
}

Expand Down
Loading