-
-
Notifications
You must be signed in to change notification settings - Fork 34.4k
free-threading: PyImport_AddModuleRef race condition #137422
Copy link
Copy link
Closed
Labels
3.13bugs and security fixesbugs and security fixes3.14bugs and security fixesbugs and security fixes3.15new features, bugs and security fixesnew features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)topic-free-threadingtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Metadata
Metadata
Assignees
Labels
3.13bugs and security fixesbugs and security fixes3.14bugs and security fixesbugs and security fixes3.15new features, bugs and security fixesnew features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)topic-free-threadingtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Bug report
Bug description:
On a NoGIL interpreter, if two threads call PyImport_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 in
sys.modules.The race condition is actually in the helper function import_add_module:
cpython/Python/import.c
Lines 319 to 335 in a50822f
if both threads call
PyMapping_GetOptionalItembefore either has calledPyObject_SetItem, you will get two different modules.Context
Each SWIG module calls
PyImport_AddModuleRefto 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 to
PyImport_AddModuleRefalways happens insideSWIG_init, which is an alias forPyInit_<modulename>which holds the GIL.This race condition only affects lazy initialisation patterns, where
PyImport_AddModuleRefis executed for the first time after module init.CPython versions tested on:
CPython main branch
Operating systems tested on:
No response
Linked PRs