Skip to content

Commit e5fe017

Browse files
[3.11] gh-105375: Harden pyexpat initialisation (#105606) (#105668)
(cherry picked from commit 20a56d8) Add proper error handling to add_errors_module() to prevent exceptions from possibly being overwritten.
1 parent f98d475 commit e5fe017

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Harden :mod:`pyexpat` error handling during module initialisation to prevent
2+
exceptions from possibly being overwritten, and objects from being
3+
dereferenced twice.

Modules/pyexpat.c

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1768,14 +1768,18 @@ add_error(PyObject *errors_module, PyObject *codes_dict,
17681768
static int
17691769
add_errors_module(PyObject *mod)
17701770
{
1771+
// add_submodule() returns a borrowed ref.
17711772
PyObject *errors_module = add_submodule(mod, MODULE_NAME ".errors");
17721773
if (errors_module == NULL) {
17731774
return -1;
17741775
}
17751776

17761777
PyObject *codes_dict = PyDict_New();
1778+
if (codes_dict == NULL) {
1779+
return -1;
1780+
}
17771781
PyObject *rev_codes_dict = PyDict_New();
1778-
if (codes_dict == NULL || rev_codes_dict == NULL) {
1782+
if (rev_codes_dict == NULL) {
17791783
goto error;
17801784
}
17811785

@@ -1796,19 +1800,17 @@ add_errors_module(PyObject *mod)
17961800
goto error;
17971801
}
17981802

1799-
Py_INCREF(codes_dict);
1800-
if (PyModule_AddObject(errors_module, "codes", codes_dict) < 0) {
1801-
Py_DECREF(codes_dict);
1803+
int rc = PyModule_AddObjectRef(errors_module, "codes", codes_dict);
1804+
Py_CLEAR(codes_dict);
1805+
if (rc < 0) {
18021806
goto error;
18031807
}
1804-
Py_CLEAR(codes_dict);
18051808

1806-
Py_INCREF(rev_codes_dict);
1807-
if (PyModule_AddObject(errors_module, "messages", rev_codes_dict) < 0) {
1808-
Py_DECREF(rev_codes_dict);
1809+
rc = PyModule_AddObjectRef(errors_module, "messages", rev_codes_dict);
1810+
Py_CLEAR(rev_codes_dict);
1811+
if (rc < 0) {
18091812
goto error;
18101813
}
1811-
Py_CLEAR(rev_codes_dict);
18121814

18131815
return 0;
18141816

0 commit comments

Comments
 (0)