Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
gh-152682: Fix NULL dereference on OOM in `symtable_visit_type_param_…
…bound_or_default` (GH-152684)

In `symtable_visit_type_param_bound_or_default()`, when a reserved name
(e.g. `__classdict__`) is used as a type parameter, `PyUnicode_FromFormat()`
is called to build the SyntaxError message. If the allocation fails and
returns NULL, the subsequent `PyErr_SetObject()` and `Py_DECREF()` calls
would dereference NULL, causing a segfault.

Fix by returning 0 immediately when `PyUnicode_FromFormat()` returns NULL.
This propagates the MemoryError set by `PyUnicode_FromFormat()`.

The bug was introduced in gh-128632 (commit 891c61c).
(cherry picked from commit 10ed03e)

Co-authored-by: Petr Vaganov <petrvaganoff@gmail.com>
  • Loading branch information
petrvaganoff authored and miss-islington committed Jun 30, 2026
commit ef59f2dbc1ec7a7c9f72eec6c2ed8071b4648011
17 changes: 17 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -2244,6 +2244,7 @@ def f(x: *b)
import unittest

from test import support
from test.support.script_helper import assert_python_ok

class SyntaxTestCase(unittest.TestCase):

Expand Down Expand Up @@ -2496,6 +2497,22 @@ class A:
class B[{name}]: pass
""", "<testcase>", mode="exec")

@support.nomemtest
def test_disallowed_type_param_names_oom(self):
# gh-152682: Don't crash on OOM when formatting the SyntaxError message
# in symtable_visit_type_param_bound_or_default.
code = textwrap.dedent("""\
import _testcapi
_testcapi.set_nomemory(0)
try:
compile("class A[__classdict__]: pass", "<string>", "exec")
except MemoryError:
pass
else:
raise RuntimeError('MemoryError not raised')
""")
assert_python_ok("-c", code)

@support.cpython_only
def test_nested_named_except_blocks(self):
code = ""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix NULL pointer dereference in :func:`compile` when a reserved name (e.g.
``__classdict__``) is used as a type parameter name and memory allocation
fails while formatting the error message.
3 changes: 3 additions & 0 deletions Python/symtable.c
Original file line number Diff line number Diff line change
Expand Up @@ -2318,6 +2318,9 @@ symtable_visit_type_param_bound_or_default(

PyObject *error_msg = PyUnicode_FromFormat("reserved name '%U' cannot be "
"used for type parameter", name);
if (error_msg == NULL) {
return 0;
}
PyErr_SetObject(PyExc_SyntaxError, error_msg);
Py_DECREF(error_msg);
PyErr_RangedSyntaxLocationObject(st->st_filename,
Expand Down
Loading