]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.14] gh-140593: Fix a memory leak in function `my_ElementDeclHandler` of `pyexpat...
authorSebastian Pipping <sebastian@pipping.org>
Sun, 26 Oct 2025 15:19:18 +0000 (16:19 +0100)
committerGitHub <noreply@github.com>
Sun, 26 Oct 2025 15:19:18 +0000 (15:19 +0000)
[3.14] gh-140593: Fix a memory leak in function `my_ElementDeclHandler` of `pyexpat` (GH-140602)

Ensure that the memory allocated for the content model
passed to `my_ElementDeclHandler` is freed in all error
paths.

(cherry picked from commit e34a5e33049ce845de646cf24a498766a2da3586)

Lib/test/test_pyexpat.py
Misc/NEWS.d/next/Library/2025-10-25-21-26-16.gh-issue-140593.OxlLc9.rst [new file with mode: 0644]
Modules/pyexpat.c

index a0914304638a962a3d93c8af2f79358e3a633220..5c8189b33c32859ffa1cc14d329fc94c0bc152f0 100644 (file)
@@ -4,6 +4,7 @@
 import os
 import sys
 import sysconfig
+import textwrap
 import unittest
 import traceback
 from io import BytesIO
@@ -668,6 +669,23 @@ class ChardataBufferTest(unittest.TestCase):
         parser.Parse(xml2, True)
         self.assertEqual(self.n, 4)
 
+class ElementDeclHandlerTest(unittest.TestCase):
+    def test_trigger_leak(self):
+        # Unfixed, this test would leak the memory of the so-called
+        # "content model" in function ``my_ElementDeclHandler`` of pyexpat.
+        # See https://github.com/python/cpython/issues/140593.
+        data = textwrap.dedent('''\
+            <!DOCTYPE quotations SYSTEM "quotations.dtd" [
+                <!ELEMENT root ANY>
+            ]>
+            <root/>
+        ''').encode('UTF-8')
+
+        parser = expat.ParserCreate()
+        parser.NotStandaloneHandler = lambda: 1.234  # arbitrary float
+        parser.ElementDeclHandler = lambda _1, _2: None
+        self.assertRaises(TypeError, parser.Parse, data, True)
+
 class MalformedInputTest(unittest.TestCase):
     def test1(self):
         xml = b"\0\r\n"
diff --git a/Misc/NEWS.d/next/Library/2025-10-25-21-26-16.gh-issue-140593.OxlLc9.rst b/Misc/NEWS.d/next/Library/2025-10-25-21-26-16.gh-issue-140593.OxlLc9.rst
new file mode 100644 (file)
index 0000000..612ad82
--- /dev/null
@@ -0,0 +1,3 @@
+:mod:`xml.parsers.expat`: Fix a memory leak that could affect users with
+:meth:`~xml.parsers.expat.xmlparser.ElementDeclHandler` set to a custom
+element declaration handler. Patch by Sebastian Pipping.
index 502ebcdc56eb37e859ea8355080100839dc6f735..d55ad3cdeef2a8af4107303a52c6810e8bd13739 100644 (file)
@@ -597,7 +597,7 @@ my_ElementDeclHandler(void *userData,
         PyObject *modelobj, *nameobj;
 
         if (PyErr_Occurred())
-            return;
+            goto finally;
 
         if (flush_character_buffer(self) < 0)
             goto finally;