8000 [3.12] gh-105375: Harden pyexpat initialisation (#105606) (#105669) · python/cpython@d310fc7 · GitHub
[go: up one dir, main page]

Skip to content

Commit d310fc7

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

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-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: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,14 +1775,18 @@ add_error(PyObject *errors_module, PyObject *codes_dict,
17751775
static int
17761776
add_errors_module(PyObject *mod)
17771777
{
1778+
// add_submodule() returns a borrowed ref.
17781779
PyObject *errors_module = add_submodule(mod, MODULE_NAME ".errors");
17791780
if (errors_module == NULL) {
17801781
return -1;
17811782
}
17821783

17831784
PyObject *codes_dict = PyDict_New();
1785+
if (codes_dict == NULL) {
1786+
return -1;
1787+
}
17841788
PyObject *rev_codes_dict = PyDict_New();
1785-
if (codes_dict == NULL || rev_codes_dict == NULL) {
1789+
if (rev_codes_dict == NULL) {
17861790
goto error;
17871791
}
17881792

@@ -1803,17 +1807,17 @@ add_errors_module(PyObject *mod)
18031807
goto error;
18041808
}
18051809

1806-
if (PyModule_AddObject(errors_module, "codes", Py_NewRef(codes_dict)) < 0) {
1807-
Py_DECREF(codes_dict);
1810+
int rc = PyModule_AddObjectRef(errors_module, "codes", codes_dict);
1811+
Py_CLEAR(codes_dict);
1812+
if (rc < 0) {
18081813
goto error;
18091814
}
1810-
Py_CLEAR(codes_dict);
18111815

1812-
if (PyModule_AddObject(errors_module, "messages", Py_NewRef(rev_codes_dict)) < 0) {
1813-
Py_DECREF(rev_codes_dict);
1816+
rc = PyModule_AddObjectRef(errors_module, "messages", rev_codes_dict);
1817+
Py_CLEAR(rev_codes_dict);
1818+
if (rc < 0) {
18141819
goto error;
18151820
}
1816-
Py_CLEAR(rev_codes_dict);
18171821

18181822
return 0;
18191823

0 commit comments

Comments
 (0)
0