Skip to content

gh-152741: Publish thread states to the interpreter's thread list only after they are fully initialized - #156202

Open
kumaraditya303 wants to merge 5 commits into
python:mainfrom
kumaraditya303:gh-152741-defer-tstate-publish
Open

kumaraditya303 wants to merge 5 commits into
python:mainfrom
kumaraditya303:gh-152741-defer-tstate-publish

Conversation

@kumaraditya303

@kumaraditya303 kumaraditya303 commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

…er-tstate-publish

# Conflicts:
#	Python/pystate.c
Comment thread Python/pystate.c
Comment on lines -1718 to -1720
// Add the new thread state to the interpreter.
PyThreadState *old_head = interp->threads.head;
add_threadstate(interp, (PyThreadState *)tstate, old_head);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex flagged that moving add_threadstate() into bind_tstate() introduces a potential use after free caused by a race with interpreter shutdown. I think it's right. Here's the race:

  1. A new daemon thread, D, is started, but something causes a delay between thread creation and when it's bound.
  2. Another thread finalizes the interpreter, but because D's thread state hasn't been inserted into the thread list, finalization doesn't see it and doesn't set its state to _Py_THREAD_SHUTTING_DOWN.
  3. D resumes. Its state is still _Py_THREAD_DETACHED so it continues normal execution and attempts to dereference tstate->interp. This results in either interacting with a finalized interpreter (the main interpreter) or freed memory (a subinterpreter).

@bedevere-app

bedevere-app Bot commented Nov 11, 2026

Copy link
Copy Markdown

When you're done making the requested changes, leave the comment: I have made the requested changes; please review again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants