]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] gh-105375: Harden pyexpat initialisation (#105606) (#105669)
authorErlend E. Aasland <erlend.aasland@protonmail.com>
Sun, 11 Jun 2023 21:35:13 +0000 (23:35 +0200)
committerGitHub <noreply@github.com>
Sun, 11 Jun 2023 21:35:13 +0000 (21:35 +0000)
(cherry picked from commit 20a56d8becba1a5a958b167fdb43b1a1b9228095)

Add proper error handling to add_errors_module() to prevent exceptions
from possibly being overwritten.

Misc/NEWS.d/next/Library/2023-06-09-23-00-13.gh-issue-105605.YuwqxY.rst [new file with mode: 0644]
Modules/pyexpat.c

diff --git a/Misc/NEWS.d/next/Library/2023-06-09-23-00-13.gh-issue-105605.YuwqxY.rst b/Misc/NEWS.d/next/Library/2023-06-09-23-00-13.gh-issue-105605.YuwqxY.rst
new file mode 100644 (file)
index 0000000..5fba6d2
--- /dev/null
@@ -0,0 +1,3 @@
+Harden :mod:`pyexpat` error handling during module initialisation to prevent
+exceptions from possibly being overwritten, and objects from being
+dereferenced twice.
index 92f594ab63ea2a06208ad36fc99d43f7e81c441f..b21360419d6a144f9cf1c5fc6b0bf06acbc02e85 100644 (file)
@@ -1775,14 +1775,18 @@ add_error(PyObject *errors_module, PyObject *codes_dict,
 static int
 add_errors_module(PyObject *mod)
 {
+    // add_submodule() returns a borrowed ref.
     PyObject *errors_module = add_submodule(mod, MODULE_NAME ".errors");
     if (errors_module == NULL) {
         return -1;
     }
 
     PyObject *codes_dict = PyDict_New();
+    if (codes_dict == NULL) {
+        return -1;
+    }
     PyObject *rev_codes_dict = PyDict_New();
-    if (codes_dict == NULL || rev_codes_dict == NULL) {
+    if (rev_codes_dict == NULL) {
         goto error;
     }
 
@@ -1803,17 +1807,17 @@ add_errors_module(PyObject *mod)
         goto error;
     }
 
-    if (PyModule_AddObject(errors_module, "codes", Py_NewRef(codes_dict)) < 0) {
-        Py_DECREF(codes_dict);
+    int rc = PyModule_AddObjectRef(errors_module, "codes", codes_dict);
+    Py_CLEAR(codes_dict);
+    if (rc < 0) {
         goto error;
     }
-    Py_CLEAR(codes_dict);
 
-    if (PyModule_AddObject(errors_module, "messages", Py_NewRef(rev_codes_dict)) < 0) {
-        Py_DECREF(rev_codes_dict);
+    rc = PyModule_AddObjectRef(errors_module, "messages", rev_codes_dict);
+    Py_CLEAR(rev_codes_dict);
+    if (rc < 0) {
         goto error;
     }
-    Py_CLEAR(rev_codes_dict);
 
     return 0;