Skip to content

Commit d57d270

Browse files
oprypincopybara-github
authored andcommitted
Fix a crash that happens during shutdown due to looking up modules in the cache
The crash happens only since Python 3.13. Conveniently, Python 3.13 introduces a function to check if the interpreter is shutting down at the moment. There was a related issue #22067 and related commit 87de6f7 but it appears that the fix was incomplete. What actually causes a crash during shutdown is using `PyState_FindModule`, and `PyUpb_ModuleState_MaybeGet` still calls that anyway. PiperOrigin-RevId: 807361381
1 parent badaf41 commit d57d270

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

python/protobuf.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,12 @@ static struct PyModuleDef module_def = {PyModuleDef_HEAD_INIT,
5858
// -----------------------------------------------------------------------------
5959

6060
PyUpb_ModuleState* PyUpb_ModuleState_MaybeGet(void) {
61+
#if PY_VERSION_HEX >= 0x030D0000 // >= 3.13
62+
/* Calling `PyState_FindModule` during interpreter shutdown causes a crash. */
63+
if (Py_IsFinalizing()) {
64+
return NULL;
65+
}
66+
#endif
6167
PyObject* module = PyState_FindModule(&module_def);
6268
return module ? PyModule_GetState(module) : NULL;
6369
}

0 commit comments

Comments
 (0)