Skip to content

Commit ed03895

Browse files
[3.12] gh-105375: Improve error handling in PyUnicode_BuildEncodingMap() (GH-105491) (#105661)
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 db5022c commit ed03895

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
@@ -7934,25 +7934,30 @@ PyUnicode_BuildEncodingMap(PyObject* string)
79347934

79357935
if (need_dict) {
79367936
PyObject *result = PyDict_New();
7937-
PyObject *key, *value;
79387937
if (!result)
79397938
return NULL;
79407939
for (i = 0; i < length; i++) {
7941-
key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
7942-
value = PyLong_FromLong(i);
7943-
if (!key || !value)
7944-
goto failed1;
7945-
if (PyDict_SetItem(result, key, value) == -1)
7946-
goto failed1;
7940+
Py_UCS4 c = PyUnicode_READ(kind, data, i);
7941+
PyObject *key = PyLong_FromLong(c);
7942+
if (key == NULL) {
7943+
Py_DECREF(result);
7944+
return NULL;
7945+
}
7946+
PyObject *value = PyLong_FromLong(i);
7947+
if (value == NULL) {
7948+
Py_DECREF(key);
7949+
Py_DECREF(result);
7950+
return NULL;
7951+
}
7952+
int rc = PyDict_SetItem(result, key, value);
79477953
Py_DECREF(key);
79487954
Py_DECREF(value);
7955+
if (rc < 0) {
7956+
Py_DECREF(result);
7957+
return NULL;
7958+
}
79497959
}
79507960
return result;
7951-
failed1:
7952-
Py_XDECREF(key);
7953-
Py_XDECREF(value);
7954-
Py_DECREF(result);
7955-
return NULL;
79567961
}
79577962

79587963
/* Create a three-level trie */

0 commit comments

Comments
 (0)