Skip to content

Commit aee9046

Browse files
[3.14] gh-148891: prevent crash in HAMT caused by GC during traverse (GH-148928) (#161592)
gh-148891: prevent crash in HAMT caused by GC during traverse (GH-148928) `_PyHamt_Assoc` allocates HAMT nodes, which can trigger GC. A weakref callback or finaliser fired during GC could re-enter `contextvar_set`, replacing `ctx->ctx_vars` via `Py_SETREF` and freeing the old HAMT while `_PyHamt_Assoc` was still traversing it, causing a use-after-free. Hold a strong reference to `ctx->ctx_vars` during the `_PyHamt_Assoc` call, so that a re-entrant free cannot affect the HAMT being traversed. (cherry picked from commit 1798d4f) Co-authored-by: Thomas Kowalski <thom.kowa@gmail.com>
1 parent ac1d49f commit aee9046

2 files changed

Lines changed: 11 additions & 1 deletion

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a crash in :func:`contextvars.Context.run` where a GC invocation could free the current HAMT during traverse.

‎Python/context.c‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -860,8 +860,13 @@ contextvar_set(PyContextVar *var, PyObject *val)
860860
return -1;
861861
}
862862

863+
// gh-148891: Make a strong reference so a GC during _PyHamt_Assoc will
864+
// not free the HAMT during traversal.
865+
PyHamtObject *old_vars = context_get_current_vars(ctx);
866+
Py_INCREF(old_vars);
863867
PyHamtObject *new_vars = _PyHamt_Assoc(
864-
context_get_current_vars(ctx), (PyObject *)var, val);
868+
old_vars, (PyObject *)var, val);
869+
Py_DECREF(old_vars);
865870
if (new_vars == NULL) {
866871
return -1;
867872
}
@@ -888,8 +893,12 @@ contextvar_del(PyContextVar *var)
888893
return -1;
889894
}
890895

896+
// gh-148891: Make a strong reference so a GC during _PyHamt_Without will
897+
// not free the HAMT during traversal.
891898
PyHamtObject *vars = context_get_current_vars(ctx);
899+
Py_INCREF(vars);
892900
PyHamtObject *new_vars = _PyHamt_Without(vars, (PyObject *)var);
901+
Py_DECREF(vars);
893902
if (new_vars == NULL) {
894903
return -1;
895904
}

0 commit comments

Comments
 (0)