Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.7k
Description
Bug report
Bug description:
On a NoGIL interpreter, if two threads callPyImport_AddModuleRef for the same module name at the same time, and that module does not exist yet, it is possible that the two calls to the function return two different objects, only one of which is stored insys.modules.
The race condition is actually in the helper function import_add_module:
Lines 319 to 335 ina50822f
| PyObject*m; | |
| if (PyMapping_GetOptionalItem(modules,name,&m)<0) { | |
| returnNULL; | |
| } | |
| if (m!=NULL&&PyModule_Check(m)) { | |
| returnm; | |
| } | |
| Py_XDECREF(m); | |
| m=PyModule_NewObject(name); | |
| if (m==NULL) | |
| returnNULL; | |
| if (PyObject_SetItem(modules,name,m)!=0) { | |
| Py_DECREF(m); | |
| returnNULL; | |
| } | |
| returnm; |
if both threads call
PyMapping_GetOptionalItem before either has calledPyObject_SetItem, you will get two different modules.Context
Each SWIG module callsPyImport_AddModuleRef to retrieve or initialise a shared global state module with the hardcoded nameswig_runtime_data5, and then stores its pointer in a module-local global variable.
SWIG is actually immune from this race condition because the call toPyImport_AddModuleRef always happens insideSWIG_init, which is an alias forPyInit_<modulename> which holds the GIL.
This race condition only affects lazy initialisation patterns, wherePyImport_AddModuleRef is executed for the first time after module init.
CPython versions tested on:
CPython main branch
Operating systems tested on:
No response