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
13 changes: 13 additions & 0 deletions Lib/test/test_xml_etree.py
Original file line number Diff line number Diff line change
Expand Up @@ -3190,6 +3190,19 @@ def __deepcopy__(self, memo):
self.assertEqual([c.tag for c in children[3:]],
[a.tag, b.tag, a.tag, b.tag])

@support.skip_if_unlimited_stack_size
@support.skip_emscripten_stack_overflow()
@support.skip_wasi_stack_overflow()
def test_deeply_nested_deepcopy(self):
# This should raise a RecursionError and not crash.
# See https://github.com/python/cpython/issues/148801.
root = cur = ET.Element('s')
for _ in range(150_000):
cur = ET.SubElement(cur, 'u')
with support.infinite_recursion():
with self.assertRaises(RecursionError):
copy.deepcopy(root)


class MutationDeleteElementPath(str):
def __new__(cls, elem, *args):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:mod:`xml.etree.ElementTree`: Fix a crash in :meth:`Element.__deepcopy__
<object.__deepcopy__>` on deeply nested trees.
16 changes: 14 additions & 2 deletions Modules/_elementtree.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#endif

#include "Python.h"
#include "pycore_ceval.h" // _Py_EnterRecursiveCall()
#include "pycore_dict.h" // _PyDict_CopyAsDict()
#include "pycore_pyhash.h" // _Py_HashSecret
#include "pycore_tuple.h" // _PyTuple_FromPair
Expand Down Expand Up @@ -818,18 +819,25 @@ _elementtree_Element___deepcopy___impl(ElementObject *self, PyObject *memo)
PyObject* tail;
PyObject* id;

if (_Py_EnterRecursiveCall(" in Element.__deepcopy__")) {
return NULL;
}

PyTypeObject *tp = Py_TYPE(self);
elementtreestate *st = get_elementtree_state_by_type(tp);
// The deepcopy() helper takes care of incrementing the refcount
// of the object to copy so to avoid use-after-frees.
tag = deepcopy(st, self->tag, memo);
if (!tag)
if (!tag) {
_Py_LeaveRecursiveCall();
return NULL;
}

if (self->extra && self->extra->attrib) {
attrib = deepcopy(st, self->extra->attrib, memo);
if (!attrib) {
Py_DECREF(tag);
_Py_LeaveRecursiveCall();
return NULL;
}
} else {
Expand All @@ -841,8 +849,10 @@ _elementtree_Element___deepcopy___impl(ElementObject *self, PyObject *memo)
Py_DECREF(tag);
Py_XDECREF(attrib);

if (!element)
if (!element) {
_Py_LeaveRecursiveCall();
return NULL;
}

text = deepcopy(st, JOIN_OBJ(self->text), memo);
if (!text)
Expand Down Expand Up @@ -904,9 +914,11 @@ _elementtree_Element___deepcopy___impl(ElementObject *self, PyObject *memo)
if (i < 0)
goto error;

_Py_LeaveRecursiveCall();
return (PyObject*) element;

error:
_Py_LeaveRecursiveCall();
Py_DECREF(element);
return NULL;
}
Expand Down
Loading