Skip to content
Open
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
20 changes: 19 additions & 1 deletion Lib/test/test_xml_etree_c.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import io
import struct
from test import support
from test.support.import_helper import import_fresh_module
from test.support.import_helper import import_fresh_module, import_module
import types
import unittest

Expand Down Expand Up @@ -183,6 +183,24 @@ def __hash__(self):
r = e.get(X())
self.assertIsNone(r)

@unittest.skipIf(support.Py_TRACE_REFS,
'Py_TRACE_REFS conflicts with testcapi.set_nomemory')
def test_iter_oom_no_crash(self):
# gh-148731: OOM while creating an Element iterator should raise
# MemoryError without crashing while deallocating a partially
# initialized iterator object.
testcapi = import_module('_testcapi')
element = cET.Element('root')
raised = False
testcapi.set_nomemory(1, 2)
try:
element.iter()
except MemoryError:
raised = True
finally:
testcapi.remove_mem_hooks()
self.assertTrue(raised, "MemoryError not raised")
Comment thread
gz83 marked this conversation as resolved.

@support.cpython_only
def test_immutable_types(self):
root = cET.fromstring('<a></a>')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a crash in :mod:`xml.etree.ElementTree` when
:meth:`~xml.etree.ElementTree.Element.iter` fails with :exc:`MemoryError`
while creating the C accelerator iterator.
5 changes: 3 additions & 2 deletions Modules/_elementtree.c
Original file line number Diff line number Diff line change
Expand Up @@ -2359,6 +2359,9 @@ create_elementiter(elementtreestate *st, ElementObject *self, PyObject *tag,
if (!it)
return NULL;

it->parent_stack_used = 0;
it->parent_stack_size = INIT_PARENT_STACK_SIZE;

it->sought_tag = Py_NewRef(tag);
it->gettext = gettext;
it->root_element = (ElementObject*)Py_NewRef(self);
Expand All @@ -2369,8 +2372,6 @@ create_elementiter(elementtreestate *st, ElementObject *self, PyObject *tag,
PyErr_NoMemory();
return NULL;
}
it->parent_stack_used = 0;
it->parent_stack_size = INIT_PARENT_STACK_SIZE;

PyObject_GC_Track(it);

Expand Down
Loading