Skip to content
Merged
30 changes: 29 additions & 1 deletion Lib/test/test_atexit.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import atexit
import os
import subprocess
import textwrap
import unittest
from test import support
from test.support import script_helper
from test.support import SuppressCrashReport, script_helper
from test.support import threading_helper

class GeneralTest(unittest.TestCase):
Expand Down Expand Up @@ -189,6 +190,33 @@ def callback():
self.assertEqual(os.read(r, len(expected)), expected)
os.close(r)

# Python built with Py_TRACE_REFS fail with a fatal error in
# _PyRefchain_Trace() on memory allocation error.
@unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build')
def test_atexit_with_low_memory(self):
# gh-140080: Test that setting low memory after registering an atexit
# callback doesn't cause an infinite loop during finalization.
user_input = textwrap.dedent("""
import atexit
import _testcapi

def callback():
print("hello")
pass

atexit.register(callback)
# Simulate low memory condition
_testcapi.set_nomemory(0)
""")
with SuppressCrashReport():
with script_helper.spawn_python('-c', user_input,
stderr=subprocess.PIPE) as p:
p.wait()
output = p.stdout.read()

self.assertIn(p.returncode, (0, 1))
self.assertNotIn(b"hello", output)


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix hang during finalization when attempting to call :mod:`atexit` handlers under no memory.
1 change: 1 addition & 0 deletions Modules/atexitmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ atexit_callfuncs(struct atexit_state *state)
{
PyErr_FormatUnraisable("Exception ignored while "
"copying atexit callbacks");
atexit_cleanup(state);
return;
}

Expand Down
Loading