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
17 changes: 17 additions & 0 deletions Lib/test/test_ast/test_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,23 @@ def test_AST_objects(self):
# "ast.AST constructor takes 0 positional arguments"
ast.AST(2)

def test_AST_fields_NULL_check(self):
# See: https://github.com/python/cpython/issues/126105
old_value = ast.AST._fields

def cleanup():
ast.AST._fields = old_value
self.addCleanup(cleanup)

del ast.AST._fields

msg = 'AST has no fields'
# Both examples used to crash:
with self.assertRaisesRegex(TypeError, msg):
ast.AST(arg1=123)
with self.assertRaisesRegex(TypeError, msg):
ast.AST()

def test_AST_garbage_collection(self):
class X:
pass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix a crash in :mod:`ast` when ``_fields`` attribute is deleted.
18 changes: 10 additions & 8 deletions Parser/asdl_c.py
Original file line number Diff line number Diff line change
Expand Up @@ -887,16 +887,18 @@ def visitModule(self, mod):
if (PyObject_GetOptionalAttr((PyObject*)Py_TYPE(self), state->_fields, &fields) < 0) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A simpler fix would have been this, right?

    if (PyObject_GetOptionalAttr((PyObject*)Py_TYPE(self), state->_fields, &fields) <= 0) {

However, your fix is better.

goto cleanup;
}
if (fields) {
numfields = PySequence_Size(fields);
if (numfields == -1) {
goto cleanup;
}
remaining_fields = PySet_New(fields);
if (fields == NULL) {
PyErr_Format(PyExc_TypeError,
"%.400s has no fields",
_PyType_Name(Py_TYPE(self)));
goto cleanup;
}
else {
remaining_fields = PySet_New(NULL);

numfields = PySequence_Size(fields);
if (numfields == -1) {
goto cleanup;
}
remaining_fields = PySet_New(fields);
if (remaining_fields == NULL) {
goto cleanup;
}
Expand Down
18 changes: 10 additions & 8 deletions Python/Python-ast.c

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading