Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

free-threading: PyImport_AddModuleRef race condition #137422

Closed
Labels
3.13bugs and security fixes3.14bugs and security fixes3.15new features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)topic-free-threadingtype-bugAn unexpected behavior, bug, or error
@crusaderky

Description

@crusaderky

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:

cpython/Python/import.c

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 callPyMapping_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

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.13bugs and security fixes3.14bugs and security fixes3.15new features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)topic-free-threadingtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp