From 41cddc2e93a285b81fa30ac542b088bd9d0112e9 Mon Sep 17 00:00:00 2001 From: "Erlend E. Aasland" Date: Sun, 11 Jun 2023 22:02:49 +0200 Subject: [PATCH] gh-105375: Improve error handling in the sys extension module (#105611) In _PySys_AddXOptionWithError() and sys_add_xoption(), bail on first error to prevent exceptions from possibly being overwritten. --- ...-06-09-23-46-23.gh-issue-105375.9KaioS.rst | 2 ++ Python/sysmodule.c | 24 ++++++++++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2023-06-09-23-46-23.gh-issue-105375.9KaioS.rst diff --git a/Misc/NEWS.d/next/Library/2023-06-09-23-46-23.gh-issue-105375.9KaioS.rst b/Misc/NEWS.d/next/Library/2023-06-09-23-46-23.gh-issue-105375.9KaioS.rst new file mode 100644 index 00000000000..b12d7c864e7 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-06-09-23-46-23.gh-issue-105375.9KaioS.rst @@ -0,0 +1,2 @@ +Fix bugs in :mod:`sys` where exceptions could end up being overwritten +because of deferred error handling. diff --git a/Python/sysmodule.c b/Python/sysmodule.c index 70274108a97..90e5e65dcf9 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -2721,14 +2721,20 @@ _PySys_AddXOptionWithError(const wchar_t *s) const wchar_t *name_end = wcschr(s, L'='); if (!name_end) { name = PyUnicode_FromWideChar(s, -1); + if (name == NULL) { + goto error; + } value = Py_NewRef(Py_True); } else { name = PyUnicode_FromWideChar(s, name_end - s); + if (name == NULL) { + goto error; + } value = PyUnicode_FromWideChar(name_end + 1, -1); - } - if (name == NULL || value == NULL) { - goto error; + if (value == NULL) { + goto error; + } } if (PyDict_SetItem(opts, name, value) < 0) { goto error; @@ -3374,14 +3380,20 @@ sys_add_xoption(PyObject *opts, const wchar_t *s) const wchar_t *name_end = wcschr(s, L'='); if (!name_end) { name = PyUnicode_FromWideChar(s, -1); + if (name == NULL) { + goto error; + } value = Py_NewRef(Py_True); } else { name = PyUnicode_FromWideChar(s, name_end - s); + if (name == NULL) { + goto error; + } value = PyUnicode_FromWideChar(name_end + 1, -1); - } - if (name == NULL || value == NULL) { - goto error; + if (value == NULL) { + goto error; + } } if (PyDict_SetItem(opts, name, value) < 0) { goto error;