Skip to content
Merged
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
7 changes: 0 additions & 7 deletions Lib/test/_test_atexit.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,22 +47,19 @@ def func2(*args, **kwargs):
('func2', (), {}),
('func1', (1, 2), {})])

@unittest.expectedFailure # TODO: RUSTPYTHON
def test_badargs(self):
def func():
pass

# func() has no parameter, but it's called with 2 parameters
self.assert_raises_unraisable(TypeError, func, 1 ,2)

@unittest.expectedFailure # TODO: RUSTPYTHON
def test_raise(self):
def raise_type_error():
raise TypeError

self.assert_raises_unraisable(TypeError, raise_type_error)

@unittest.expectedFailure # TODO: RUSTPYTHON
def test_raise_unnormalized(self):
# bpo-10756: Make sure that an unnormalized exception is handled
# properly.
Expand All @@ -71,7 +68,6 @@ def div_zero():

self.assert_raises_unraisable(ZeroDivisionError, div_zero)

@unittest.expectedFailure # TODO: RUSTPYTHON
def test_exit(self):
self.assert_raises_unraisable(SystemExit, sys.exit)

Expand Down Expand Up @@ -122,7 +118,6 @@ def test_bound_methods(self):
atexit._run_exitfuncs()
self.assertEqual(l, [5])

@unittest.expectedFailure # TODO: RUSTPYTHON
def test_atexit_with_unregistered_function(self):
# See bpo-46025 for more info
def func():
Expand All @@ -140,7 +135,6 @@ def func():
finally:
atexit.unregister(func)

@unittest.skip("TODO: RUSTPYTHON; Hangs")
def test_eq_unregister_clear(self):
# Issue #112127: callback's __eq__ may call unregister or _clear
class Evil:
Expand All @@ -154,7 +148,6 @@ def __eq__(self, other):
atexit.unregister(Evil())
atexit._clear()

@unittest.skip("TODO: RUSTPYTHON; Hangs")
def test_eq_unregister(self):
# Issue #112127: callback's __eq__ may call unregister
def f1():
Expand Down
63 changes: 51 additions & 12 deletions crates/vm/src/stdlib/atexit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ mod atexit {

#[pyfunction]
fn register(func: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef {
vm.state.atexit_funcs.lock().push((func.clone(), args));
// Callbacks go in LIFO order (insert at front)
vm.state
.atexit_funcs
.lock()
.insert(0, Box::new((func.clone(), args)));
func
}

Expand All @@ -18,27 +22,62 @@ mod atexit {

#[pyfunction]
fn unregister(func: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let mut funcs = vm.state.atexit_funcs.lock();

let mut i = 0;
while i < funcs.len() {
if vm.bool_eq(&funcs[i].0, &func)? {
funcs.remove(i);
} else {
i += 1;
// Iterate backward (oldest to newest in LIFO list).
// Release the lock during comparison so __eq__ can call atexit functions.
let mut i = {
let funcs = vm.state.atexit_funcs.lock();
funcs.len() as isize - 1
};
while i >= 0 {
let (cb, entry_ptr) = {
let funcs = vm.state.atexit_funcs.lock();
if i as usize >= funcs.len() {
i = funcs.len() as isize;
i -= 1;
continue;
}
let entry = &funcs[i as usize];
(entry.0.clone(), &**entry as *const (PyObjectRef, FuncArgs))
};
// Lock released: __eq__ can safely call atexit functions
let eq = vm.bool_eq(&func, &cb)?;
if eq {
// The entry may have moved during __eq__. Search backward by identity.
let mut funcs = vm.state.atexit_funcs.lock();
let mut j = (funcs.len() as isize - 1).min(i);
while j >= 0 {
if core::ptr::eq(&**funcs.get(j as usize).unwrap(), entry_ptr) {
funcs.remove(j as usize);
i = j;
break;
}
j -= 1;
}
}
{
let funcs = vm.state.atexit_funcs.lock();
if i as usize >= funcs.len() {
i = funcs.len() as isize;
}
}
i -= 1;
}

Ok(())
}

#[pyfunction]
pub fn _run_exitfuncs(vm: &VirtualMachine) {
let funcs: Vec<_> = core::mem::take(&mut *vm.state.atexit_funcs.lock());
for (func, args) in funcs.into_iter().rev() {
// Callbacks stored in LIFO order, iterate forward
for entry in funcs.into_iter() {
let (func, args) = *entry;
if let Err(e) = func.call(args, vm) {
let exit = e.fast_isinstance(vm.ctx.exceptions.system_exit);
vm.run_unraisable(e, Some("Error in atexit._run_exitfuncs".to_owned()), func);
let msg = func
.repr(vm)
.ok()
.map(|r| format!("Exception ignored in atexit callback {}", r.as_wtf8()));
vm.run_unraisable(e, msg, vm.ctx.none());
if exit {
break;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/vm/src/vm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,7 @@ pub struct PyGlobalState {
pub stacksize: AtomicCell<usize>,
pub thread_count: AtomicCell<usize>,
pub hash_secret: HashSecret,
pub atexit_funcs: PyMutex<Vec<(PyObjectRef, FuncArgs)>>,
pub atexit_funcs: PyMutex<Vec<Box<(PyObjectRef, FuncArgs)>>>,
pub codec_registry: CodecsRegistry,
pub finalizing: AtomicBool,
pub warnings: WarningsState,
Expand Down
Loading