Skip to content

Commit f64b60b

Browse files
committed
gh-126105: Fix crash in ast module, when ._fields is deleted
1 parent 9b14083 commit f64b60b

4 files changed

Lines changed: 38 additions & 16 deletions

File tree

Lib/test/test_ast/test_ast.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,23 @@ def test_AST_objects(self):
8484
# "ast.AST constructor takes 0 positional arguments"
8585
ast.AST(2)
8686

87+
def test_AST_fields_NULL_check(self):
88+
# See: https://github.com/python/cpython/issues/126105
89+
old_value = ast.AST._fields
90+
91+
def cleanup():
92+
ast.AST._fields = old_value
93+
self.addCleanup(cleanup)
94+
95+
del ast.AST._fields
96+
97+
msg = 'AST has no fields'
98+
# Both examples used to crash:
99+
with self.assertRaisesRegex(TypeError, msg):
100+
ast.AST(arg1=123)
101+
with self.assertRaisesRegex(TypeError, msg):
102+
ast.AST()
103+
87104
def test_AST_garbage_collection(self):
88105
class X:
89106
pass
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a crash in :mod:`ast` when ``_fields`` attribute is deleted.

Parser/asdl_c.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -887,16 +887,18 @@ def visitModule(self, mod):
887887
if (PyObject_GetOptionalAttr((PyObject*)Py_TYPE(self), state->_fields, &fields) < 0) {
888888
goto cleanup;
889889
}
890-
if (fields) {
891-
numfields = PySequence_Size(fields);
892-
if (numfields == -1) {
893-
goto cleanup;
894-
}
895-
remaining_fields = PySet_New(fields);
890+
if (fields == NULL) {
891+
PyErr_Format(PyExc_TypeError,
892+
"%.400s has no fields",
893+
_PyType_Name(Py_TYPE(self)));
894+
goto cleanup;
896895
}
897-
else {
898-
remaining_fields = PySet_New(NULL);
896+
897+
numfields = PySequence_Size(fields);
898+
if (numfields == -1) {
899+
goto cleanup;
899900
}
901+
remaining_fields = PySet_New(fields);
900902
if (remaining_fields == NULL) {
901903
goto cleanup;
902904
}

Python/Python-ast.c

Lines changed: 10 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)