Skip to content

bpo-27946: Fix possible crash in ElementTree.Element #29915

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 12 additions & 0 deletions Lib/test/test_xml_etree_c.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,18 @@ def test_xmlpullparser_leaks(self):
del parser
support.gc_collect()

def test_dict_disappearing_during_get_item(self):
# test fix for seg fault reported in issue 27946
class X:
def __hash__(self):
e.attrib = {} # this frees e->extra->attrib
[{i: i} for i in range(1000)] # exhaust the dict keys cache
return 13

e = cET.Element("elem", {1: 2})
r = e.get(X())
self.assertIsNone(r)


@unittest.skipUnless(cET, 'requires _elementtree')
class TestAliasWorking(unittest.TestCase):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix possible crash when getting an attribute of
class:`xml.etree.ElementTree.Element` simultaneously with
replacing the ``attrib`` dict.
23 changes: 10 additions & 13 deletions Modules/_elementtree.c
Original file line number Diff line number Diff line change
Expand Up @@ -1393,22 +1393,19 @@ _elementtree_Element_get_impl(ElementObject *self, PyObject *key,
PyObject *default_value)
/*[clinic end generated code: output=523c614142595d75 input=ee153bbf8cdb246e]*/
{
PyObject* value;

if (!self->extra || !self->extra->attrib)
value = default_value;
else {
value = PyDict_GetItemWithError(self->extra->attrib, key);
if (!value) {
if (PyErr_Occurred()) {
return NULL;
}
value = default_value;
if (self->extra && self->extra->attrib) {
PyObject *attrib = self->extra->attrib;
Py_INCREF(attrib);
PyObject *value = PyDict_GetItemWithError(attrib, key);
Py_XINCREF(value);
Py_DECREF(attrib);
if (value != NULL || PyErr_Occurred()) {
return value;
}
}

Py_INCREF(value);
return value;
Py_INCREF(default_value);
return default_value;
}

static PyObject *
Expand Down