Skip to content

Commit 9986943

Browse files
[3.15] gh-159739: Skip context watchers cleared during notification (GH-160164) (#160291)
A context watcher callback can clear a later watcher while a context-switch notification is being dispatched. The dispatcher still uses its earlier snapshot of active watchers, so it calls a NULL callback and crashes; check that each callback is still registered before invoking it. Backport to 3.15 and 3.14. (cherry picked from commit 0a57626) Co-authored-by: Jelle Zijlstra <jelle@openai.com>
1 parent 23ac9a8 commit 9986943

2 files changed

Lines changed: 4 additions & 2 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Avoid a crash if a context watcher is cleared while other context watchers
2+
are being notified.

‎Python/context.c‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,8 @@ notify_context_watchers(PyThreadState *ts, PyContextEvent event, PyObject *ctx)
169169
assert(i < CONTEXT_MAX_WATCHERS);
170170
if (bits & 1) {
171171
PyContext_WatchCallback cb = interp->context_watchers[i];
172-
assert(cb != NULL);
173-
if (cb(event, ctx) < 0) {
172+
// A previous callback may have cleared this watcher.
173+
if (cb != NULL && cb(event, ctx) < 0) {
174174
PyErr_FormatUnraisable(
175175
"Exception ignored in %s watcher callback for %R",
176176
context_event_name(event), ctx);

0 commit comments

Comments
 (0)