]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.11] gh-105375: Improve error handling in PyUnicode_BuildEncodingMap() (GH-105491...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 11 Jun 2023 20:01:52 +0000 (13:01 -0700)
committerGitHub <noreply@github.com>
Sun, 11 Jun 2023 20:01:52 +0000 (20:01 +0000)
Bail on first error to prevent exceptions from possibly being overwritten.
(cherry picked from commit 555be81026fe1205d16c02f6321221381174cd07)

Co-authored-by: Erlend E. Aasland <erlend.aasland@protonmail.com>
Misc/NEWS.d/next/Core and Builtins/2023-06-08-09-25-52.gh-issue-105375.ocB7fT.rst [new file with mode: 0644]
Objects/unicodeobject.c

diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-06-08-09-25-52.gh-issue-105375.ocB7fT.rst b/Misc/NEWS.d/next/Core and Builtins/2023-06-08-09-25-52.gh-issue-105375.ocB7fT.rst
new file mode 100644 (file)
index 0000000..24fac2d
--- /dev/null
@@ -0,0 +1,2 @@
+Improve error handling in :c:func:`PyUnicode_BuildEncodingMap` where an
+exception could end up being overwritten.
index 4bdc89316a864748f704a014e1a24c207c83fef8..50deefe0adc2cc72cce9cd87c39bdb42de1bffb7 100644 (file)
@@ -8454,25 +8454,30 @@ PyUnicode_BuildEncodingMap(PyObject* string)
 
     if (need_dict) {
         PyObject *result = PyDict_New();
-        PyObject *key, *value;
         if (!result)
             return NULL;
         for (i = 0; i < length; i++) {
-            key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
-            value = PyLong_FromLong(i);
-            if (!key || !value)
-                goto failed1;
-            if (PyDict_SetItem(result, key, value) == -1)
-                goto failed1;
+            Py_UCS4 c = PyUnicode_READ(kind, data, i);
+            PyObject *key = PyLong_FromLong(c);
+            if (key == NULL) {
+                Py_DECREF(result);
+                return NULL;
+            }
+            PyObject *value = PyLong_FromLong(i);
+            if (value == NULL) {
+                Py_DECREF(key);
+                Py_DECREF(result);
+                return NULL;
+            }
+            int rc = PyDict_SetItem(result, key, value);
             Py_DECREF(key);
             Py_DECREF(value);
+            if (rc < 0) {
+                Py_DECREF(result);
+                return NULL;
+            }
         }
         return result;
-      failed1:
-        Py_XDECREF(key);
-        Py_XDECREF(value);
-        Py_DECREF(result);
-        return NULL;
     }
 
     /* Create a three-level trie */