[Python-checkins] gh-105375: Improve error handling in PyUnicode_BuildEncodingMap() (#105491)
erlend-aasland
webhook-mailer at python.org
Sun Jun 11 15:29:26 EDT 2023
https://github.com/python/cpython/commit/555be81026fe1205d16c02f6321221381174cd07
commit: 555be81026fe1205d16c02f6321221381174cd07
branch: main
author: Erlend E. Aasland <erlend.aasland at protonmail.com>
committer: erlend-aasland <erlend.aasland at protonmail.com>
date: 2023-06-11T21:29:19+02:00
summary:
gh-105375: Improve error handling in PyUnicode_BuildEncodingMap() (#105491)
Bail on first error to prevent exceptions from possibly being overwritten.
files:
A Misc/NEWS.d/next/Core and Builtins/2023-06-08-09-25-52.gh-issue-105375.ocB7fT.rst
M 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
index 0000000000000..24fac2df4d095
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2023-06-08-09-25-52.gh-issue-105375.ocB7fT.rst
@@ -0,0 +1,2 @@
+Improve error handling in :c:func:`PyUnicode_BuildEncodingMap` where an
+exception could end up being overwritten.
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
index ffb4a87d4b926..38b72de88f3c0 100644
--- a/Objects/unicodeobject.c
+++ b/Objects/unicodeobject.c
@@ -7934,25 +7934,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 */
More information about the Python-checkins
mailing list