diff --git a/Misc/NEWS.d/next/Library/2023-06-09-23-00-13.gh-issue-105605.YuwqxY.rst b/Misc/NEWS.d/next/Library/2023-06-09-23-00-13.gh-issue-105605.YuwqxY.rst new file mode 100644 index 00000000000..5fba6d293a7 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-06-09-23-00-13.gh-issue-105605.YuwqxY.rst @@ -0,0 +1,3 @@ +Harden :mod:`pyexpat` error handling during module initialisation to prevent +exceptions from possibly being overwritten, and objects from being +dereferenced twice. diff --git a/Modules/pyexpat.c b/Modules/pyexpat.c index 27f2d0a6a0f..e3333fff00b 100644 --- a/Modules/pyexpat.c +++ b/Modules/pyexpat.c @@ -1775,14 +1775,18 @@ add_error(PyObject *errors_module, PyObject *codes_dict, static int add_errors_module(PyObject *mod) { + // add_submodule() returns a borrowed ref. PyObject *errors_module = add_submodule(mod, MODULE_NAME ".errors"); if (errors_module == NULL) { return -1; } PyObject *codes_dict = PyDict_New(); + if (codes_dict == NULL) { + return -1; + } PyObject *rev_codes_dict = PyDict_New(); - if (codes_dict == NULL || rev_codes_dict == NULL) { + if (rev_codes_dict == NULL) { goto error; } @@ -1803,17 +1807,17 @@ add_errors_module(PyObject *mod) goto error; } - if (PyModule_AddObject(errors_module, "codes", Py_NewRef(codes_dict)) < 0) { - Py_DECREF(codes_dict); - goto error; - } + int rc = PyModule_AddObjectRef(errors_module, "codes", codes_dict); Py_CLEAR(codes_dict); - - if (PyModule_AddObject(errors_module, "messages", Py_NewRef(rev_codes_dict)) < 0) { - Py_DECREF(rev_codes_dict); + if (rc < 0) { goto error; } + + rc = PyModule_AddObjectRef(errors_module, "messages", rev_codes_dict); Py_CLEAR(rev_codes_dict); + if (rc < 0) { + goto error; + } return 0;