Skip to content

Commit 9187747

Browse files
[3.11] gh-105375: Improve error handling in PyUnicode_BuildEncodingMap() (GH-105491) (#105662)
Bail on first error to prevent exceptions from possibly being overwritten. (cherry picked from commit 555be81) Co-authored-by: Erlend E. Aasland <[email protected]>
1 parent 05c73e1 commit 9187747

File tree

2 files changed

+19
-12
lines changed

2 files changed

+19
-12
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve error handling in :c:func:`PyUnicode_BuildEncodingMap` where an
2+
exception could end up being overwritten.

Objects/unicodeobject.c

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8454,25 +8454,30 @@ PyUnicode_BuildEncodingMap(PyObject* string)
84548454

84558455
if (need_dict) {
84568456
PyObject *result = PyDict_New();
8457-
PyObject *key, *value;
84588457
if (!result)
84598458
return NULL;
84608459
for (i = 0; i < length; i++) {
8461-
key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
8462-
value = PyLong_FromLong(i);
8463-
if (!key || !value)
8464-
goto failed1;
8465-
if (PyDict_SetItem(result, key, value) == -1)
8466-
goto failed1;
8460+
Py_UCS4 c = PyUnicode_READ(kind, data, i);
8461+
PyObject *key = PyLong_FromLong(c);
8462+
if (key == NULL) {
8463+
Py_DECREF(result);
8464+
return NULL;
8465+
}
8466+
PyObject *value = PyLong_FromLong(i);
8467+
if (value == NULL) {
8468+
Py_DECREF(key);
8469+
Py_DECREF(result);
8470+
return NULL;
8471+
}
8472+
int rc = PyDict_SetItem(result, key, value);
84678473
Py_DECREF(key);
84688474
Py_DECREF(value);
8475+
if (rc < 0) {
8476+
Py_DECREF(result);
8477+
return NULL;
8478+
}
84698479
}
84708480
return result;
8471-
failed1:
8472-
Py_XDECREF(key);
8473-
Py_XDECREF(value);
8474-
Py_DECREF(result);
8475-
return NULL;
84768481
}
84778482

84788483
/* Create a three-level trie */

0 commit comments

Comments
 (0)