[3.13] gh-144601: Avoid sharing exception objects raised in a PyInit function across multiple interpreters (GH-144602) (GH-144880)

(cherry picked from commit fd6b639a49)
This commit is contained in:
Peter Bierma 2026-02-16 11:05:55 -05:00 committed by GitHub
parent e701a5cb18
commit 9314ec23a6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 53 additions and 1 deletions

View file

@ -2089,13 +2089,29 @@ import_run_extension(PyThreadState *tstate, PyModInitFunction p0,
}
main_finally:
if (rc < 0) {
_Py_ext_module_loader_result_apply_error(&res, name_buf);
}
/* Switch back to the subinterpreter. */
if (switched) {
// gh-144601: The exception object can't be transferred across
// interpreters. Instead, we print out an unraisable exception, and
// then raise a different exception for the calling interpreter.
if (rc < 0) {
assert(PyErr_Occurred());
PyErr_FormatUnraisable("Exception while importing from subinterpreter");
}
assert(main_tstate != tstate);
switch_back_from_main_interpreter(tstate, main_tstate, mod);
/* Any module we got from the init function will have to be
* reloaded in the subinterpreter. */
mod = NULL;
if (rc < 0) {
PyErr_SetString(PyExc_ImportError,
"failed to import from subinterpreter due to exception");
goto error;
}
}
/*****************************************************************/
@ -2104,7 +2120,6 @@ import_run_extension(PyThreadState *tstate, PyModInitFunction p0,
/* Finally we handle the error return from _PyImport_RunModInitFunc(). */
if (rc < 0) {
_Py_ext_module_loader_result_apply_error(&res, name_buf);
goto error;
}