Skip to content

Commit fd3304f

Browse files
gh-146022: Fix free-threading crash in xml.etree.ElementTree's Element
_elementtree.c declares Py_MOD_GIL_NOT_USED but has no locking at all, so concurrent readers and writers race on the Element type's internal ElementObjectExtra struct (self->extra). For example, Element.clear() sets self->extra to NULL and frees the old struct while another thread concurrently indexes or measures the length of the same element, causing a use-after-free/NULL-deref segfault. Add the standard Py_BEGIN/END_CRITICAL_SECTION locking to every raw C slot (__getitem__, __setitem__, __len__, __bool__, and the two subscript slots, via the established *_lock_held extraction pattern for functions with multiple return paths) and every tag/text/tail/attrib property accessor, and add @critical_section Argument Clinic annotations to the methods that read or write self->extra (append, clear, extend, insert, remove, set, get, items, keys, find/findtext/ findall, __copy__/__deepcopy__/__sizeof__/__getstate__/__setstate__). Verified against the reported crash reproducer (reliably segfaults without this change, does not with it), a broader multithreaded stress test exercising every touched method concurrently, and the full test_xml_etree/test_xml_etree_c suites on both a regular and a free-threaded (--disable-gil) Windows build. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent e620377 commit fd3304f

3 files changed

Lines changed: 209 additions & 67 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Fix a crash in the free-threaded build when concurrently reading and
2+
mutating an :class:`xml.etree.ElementTree.Element` (for example indexing
3+
or iterating an element from one thread while another calls
4+
:meth:`~xml.etree.ElementTree.Element.clear`). The C accelerator's
5+
``Element`` type had no locking despite declaring free-threading support;
6+
it now uses critical sections consistently across its methods, slots,
7+
and property accessors.

0 commit comments

Comments
 (0)