@@ -1923,6 +1923,39 @@ def test_keyerror_context(self):
19231923 exc2 = None
19241924
19251925
1926+ @cpython_only
1927+ # Python built with Py_TRACE_REFS fail with a fatal error in
1928+ # _PyRefchain_Trace() on memory allocation error.
1929+ @unittest .skipIf (support .Py_TRACE_REFS , 'cannot test Py_TRACE_REFS build' )
1930+ def test_exec_set_nomemory_hang (self ):
1931+ import_module ("_testcapi" )
1932+ # gh-134163: A MemoryError inside code that was wrapped by a try/except
1933+ # block would lead to an infinite loop.
1934+
1935+ # The frame_lasti needs to be greater than 257 to prevent
1936+ # PyLong_FromLong() from returning cached integers, which
1937+ # don't require a memory allocation. Prepend some dummy code
1938+ # to artificially increase the instruction index.
1939+ warmup_code = "a = list(range(0, 1))\n " * 60
1940+ user_input = warmup_code + dedent ("""
1941+ try:
1942+ import _testcapi
1943+ _testcapi.set_nomemory(0)
1944+ b = list(range(1000, 2000))
1945+ except Exception as e:
1946+ import traceback
1947+ traceback.print_exc()
1948+ """ )
1949+ with SuppressCrashReport ():
1950+ with script_helper .spawn_python ('-c' , user_input ) as p :
1951+ p .wait ()
1952+ output = p .stdout .read ()
1953+
1954+ self .assertIn (p .returncode , (0 , 1 ))
1955+ self .assertGreater (len (output ), 0 ) # At minimum, should not hang
1956+ self .assertIn (b"MemoryError" , output )
1957+
1958+
19261959class NameErrorTests (unittest .TestCase ):
19271960 def test_name_error_has_name (self ):
19281961 try :
0 commit comments