Skip to content

Commit d6cf426

Browse files
pythongh-105605: Harden pyexpat initialisation
Add proper error handling to add_errors_module() to prevent exceptions from possibly being overwritten, and objects from being decref'ed twice.
1 parent b047fa5 commit d6cf426

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
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: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1781,8 +1781,11 @@ add_errors_module(PyObject *mod)
17811781
}
17821782

17831783
PyObject *codes_dict = PyDict_New();
1784+
if (codes_dict == NULL) {
1785+
return -1;
1786+
}
17841787
PyObject *rev_codes_dict = PyDict_New();
1785-
if (codes_dict == NULL || rev_codes_dict == NULL) {
1788+
if (rev_codes_dict == NULL) {
17861789
goto error;
17871790
}
17881791

@@ -1803,17 +1806,17 @@ add_errors_module(PyObject *mod)
18031806
goto error;
18041807
}
18051808

1806-
if (PyModule_AddObject(errors_module, "codes", Py_NewRef(codes_dict)) < 0) {
1807-
Py_DECREF(codes_dict);
1809+
int rc = PyModule_AddObjectRef(errors_module, "codes", codes_dict);
1810+
Py_CLEAR(codes_dict);
1811+
if (rc < 0) {
18081812
goto error;
18091813
}
1810-
Py_CLEAR(codes_dict);
18111814

1812-
if (PyModule_AddObject(errors_module, "messages", Py_NewRef(rev_codes_dict)) < 0) {
1813-
Py_DECREF(rev_codes_dict);
1815+
rc = PyModule_AddObject(errors_module, "messages", rev_codes_dict);
1816+
Py_CLEAR(rev_codes_dict);
1817+
if (rc < 0) {
18141818
goto error;
18151819
}
1816-
Py_CLEAR(rev_codes_dict);
18171820

18181821
return 0;
18191822

0 commit comments

Comments
 (0)