Skip to content

gh-148731: Fix Element.iter() crash on OOM#148838

Open
gz83 wants to merge 1 commit intopython:mainfrom
gz83:gh-148731
Open

gh-148731: Fix Element.iter() crash on OOM#148838
gz83 wants to merge 1 commit intopython:mainfrom
gz83:gh-148731

Conversation

@gz83
Copy link
Copy Markdown

@gz83 gz83 commented Apr 21, 2026

Initialize ElementIterObject fields before allocating parent_stack so the partially initialized iterator can be safely deallocated if PyMem_New() fails.

Add a regression test covering the MemoryError path in Element.iter().

Tests run:

  • ./python -m test test_xml_etree_c
  • Reproduced the issue with the UBSan build before the fix
  • Verified that the UBSan reproducer no longer crashes after the fix

@python-cla-bot
Copy link
Copy Markdown

python-cla-bot Bot commented Apr 21, 2026

All commit authors signed the Contributor License Agreement.

CLA signed

Initialize ElementIterObject fields before allocating parent_stack so
the partially initialized iterator can be safely deallocated if
PyMem_New() fails.

Add a regression test covering the MemoryError path in Element.iter().
@gz83
Copy link
Copy Markdown
Author

gz83 commented Apr 21, 2026

@StanFromIreland

Hello, please take a look at this patch. Also, this is my first time contributing a patch to cpython, so please point out any shortcomings. Thank you!

class MiscTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.testcapi = import_module('_testcapi')
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If it is not available the entire MiscTests will be skipped?

raised = True
finally:
self.testcapi.remove_mem_hooks()
self.assertTrue(raised, "MemoryError not raised")
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

You can use:

with self.assertRaises(MemoryError):

inside the try instead.

Comment thread Modules/_elementtree.c
it->parent_stack_used = 0;
it->parent_stack_size = 0;
it->root_element = NULL;
it->sought_tag = NULL;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

These are initialised shortly after anyway?

Comment thread Modules/_elementtree.c
Comment on lines 2379 to 2380
it->parent_stack_used = 0;
it->parent_stack_size = INIT_PARENT_STACK_SIZE;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Perhaps simply moving these two lines up can fix the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants