Skip to content

The C API needs to protect state that can be deleted by finalization #134307

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
ZeroIntensity opened this issue May 20, 2025 · 1 comment
Open
Labels
3.13 bugs and security fixes 3.14 bugs and security fixes 3.15 new features, bugs and security fixes topic-C-API topic-free-threading topic-subinterpreters triaged The issue has been accepted as valid by a triager.

Comments

@ZeroIntensity
Copy link
Member

ZeroIntensity commented May 20, 2025

In the C API, we have some functions that need to access state that is deleted by finalization. For example, PyGILState_Ensure accesses the gilstate, and that can be concurrently deallocated. In that specific case, I proposed #132510 as a fix, but really, we should have a better way to protect state against a finalizing interpreter. I'm not sure whether to categorize this as a bug or a feature.

I think the best way to do this is through a finalizing counter similar to how PEP-788 proposes preventing interpreter shutdown. So, for functions that don't require an attached thread state, we need something like:

int
PySomething_Whatever(PyInterpreterState *interp)
{
    if (_PyInterpreterState_CriticalSection(interp) < 0) {
        // Interpreter has finalized
        return -1;
    }

    /* Do critical operation */

    _PyInterpreterState_EndCriticalSection(interp);
    return 0;
}

Does this approach seem reasonable to everyone?

cc @ericsnowcurrently

@ZeroIntensity ZeroIntensity added topic-subinterpreters 3.13 bugs and security fixes topic-free-threading 3.14 bugs and security fixes 3.15 new features, bugs and security fixes labels May 20, 2025
@ZeroIntensity
Copy link
Member Author

cc @colesbury as well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.13 bugs and security fixes 3.14 bugs and security fixes 3.15 new features, bugs and security fixes topic-C-API topic-free-threading topic-subinterpreters triaged The issue has been accepted as valid by a triager.
Projects
Status: Todo
Development

No branches or pull requests

2 participants