https://github.com/python/cpython/commit/aa287d7f443c2e219b43f7b804b209971964d206
commit: aa287d7f443c2e219b43f7b804b209971964d206
branch: main
author: Pengyu Lee <[email protected]>
committer: vstinner <[email protected]>
date: 2026-09-29T10:48:11Z
summary:

gh-158241: Prevent double release of assembler byte writers (#158242)

Co-authored-by: Victor Stinner <[email protected]>

files:
A 
Misc/NEWS.d/next/Core_and_Builtins/2026-09-26-23-44-44.gh-issue-158241.NZ9OSU.rst
M Lib/test/test_compile.py
M Python/assemble.c

diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py
index 553ac70d83a802..8b6a07be477dcc 100644
--- a/Lib/test/test_compile.py
+++ b/Lib/test/test_compile.py
@@ -39,6 +39,26 @@ def test_no_ending_newline(self):
     def test_empty(self):
         compile("", "<test>", "exec")
 
+    @support.requires_subprocess()
+    @support.nomemtest
+    def test_assemble_init_allocation_failure(self):
+        # gh-158241: Check error handling on MemoryError in Python/assemble.c
+        code = textwrap.dedent("""
+            from test import support
+
+            failures = 0
+            for n in range(1, 100):
+                with support.inject_memory_error_cm(n, n + 1):
+                    try:
+                        compile("x", "<test>", "exec")
+                    except MemoryError:
+                        failures += 1
+
+            if failures == 0:
+                raise AssertionError
+        """)
+        script_helper.assert_python_ok('-c', code)
+
     def test_other_newlines(self):
         compile("\r\n", "<test>", "exec")
         compile("\r", "<test>", "exec")
diff --git 
a/Misc/NEWS.d/next/Core_and_Builtins/2026-09-26-23-44-44.gh-issue-158241.NZ9OSU.rst
 
b/Misc/NEWS.d/next/Core_and_Builtins/2026-09-26-23-44-44.gh-issue-158241.NZ9OSU.rst
new file mode 100644
index 00000000000000..fd64c9b695ff2f
--- /dev/null
+++ 
b/Misc/NEWS.d/next/Core_and_Builtins/2026-09-26-23-44-44.gh-issue-158241.NZ9OSU.rst
@@ -0,0 +1,2 @@
+Fix a crash and possible code object corruption following a
+:exc:`MemoryError` while compiling Python code.
diff --git a/Python/assemble.c b/Python/assemble.c
index db9efff5e08ca9..2c8abb116b2e33 100644
--- a/Python/assemble.c
+++ b/Python/assemble.c
@@ -81,8 +81,11 @@ assemble_init(struct assembler *a, int firstlineno)
     return SUCCESS;
 error:
     PyBytesWriter_Discard(a->a_bytecode_writer);
+    a->a_bytecode_writer = NULL;
     PyBytesWriter_Discard(a->a_linetable_writer);
+    a->a_linetable_writer = NULL;
     PyBytesWriter_Discard(a->a_except_table_writer);
+    a->a_except_table_writer = NULL;
     return ERROR;
 }
 

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to