diff --git a/Lib/test/test_free_threading/test_frame.py b/Lib/test/test_free_threading/test_frame.py index bea49df557aa2c..82d1bf97d985fa 100644 --- a/Lib/test/test_free_threading/test_frame.py +++ b/Lib/test/test_free_threading/test_frame.py @@ -1,9 +1,10 @@ import functools +import gc import sys import threading import unittest -from test.support import threading_helper +from test.support import import_helper, threading_helper threading_helper.requires_working_threading(module=True) @@ -122,6 +123,267 @@ def writer(frame): run_with_frame([reader, writer, reader, writer]) + def test_concurrent_f_locals_read_values(self): + def runner(): + a = 1 + b = "hello" + c = [1, 2, 3] + for i in range(100): + a += i + + def reader(frame): + locals_dict = frame.f_locals + list(locals_dict.keys()) + list(locals_dict.values()) + + run_with_frame(reader, runner=runner) + + def test_concurrent_f_locals_write(self): + def runner(): + x = 0 + for i in range(100): + x += i + + def writer(frame): + frame.f_locals["new_var"] = 42 + + run_with_frame(writer, runner=runner) + + def test_concurrent_f_locals_read_write(self): + def runner(): + a = 1 + b = 2 + for i in range(100): + a += i + + def reader(frame): + _ = frame.f_locals.get("a") + _ = frame.f_locals.get("b") + + def writer(frame): + frame.f_locals["a"] = 42 + + run_with_frame([reader, writer, reader, writer], runner=runner) + + def test_concurrent_f_locals_iteration(self): + def runner(): + a = 1 + b = "hello" + c = [1, 2, 3] + for i in range(100): + a += i + + def iterator(frame): + for key, value in frame.f_locals.items(): + pass + + run_with_frame(iterator, runner=runner) + + def test_gen_f_locals_read_while_running(self): + # gh-144446: reading f_locals of a generator frame while the + # generator is executing on another thread. + for _ in range(5): + def gen_fn(): + x = 0 + obj = None + s = None + yield + for i in range(2000): + obj = [i] * 4 + s = str(i) * 8 + x += i + yield x + + g = gen_fn() + next(g) + frame = g.gi_frame + barrier = threading.Barrier(3) + + def runner(): + barrier.wait() + next(g) + + def reader(): + barrier.wait() + for _ in range(100): + fl = frame.f_locals + list(fl.values()) + fl.get("obj") + fl.get("s") + len(fl) + + threading_helper.run_concurrently([runner, reader, reader]) + g.close() + + def test_gen_f_locals_write_suspended(self): + # Writes through f_locals must be synchronized with resuming. + for _ in range(5): + def gen_fn(): + x = 0 + extra = None + while True: + x += 1 + yield x + + g = gen_fn() + next(g) + frame = g.gi_frame + barrier = threading.Barrier(3) + + def runner(): + barrier.wait() + for _ in range(500): + next(g) + + def writer(): + barrier.wait() + for i in range(200): + frame.f_locals["extra"] = [i] + frame.f_locals["new_var"] = i + + threading_helper.run_concurrently([runner, writer, writer]) + g.close() + + def test_gen_f_locals_dying_generator(self): + # Access f_locals while the last reference to the generator is + # dropped and the frame ownership moves to the frame object. + for _ in range(20): + def gen_fn(): + x = 42 + yield x + + g = gen_fn() + next(g) + frame = g.gi_frame + barrier = threading.Barrier(3) + ref = [g] + del g + + def dropper(): + barrier.wait() + ref.clear() + + def reader(): + barrier.wait() + for _ in range(100): + frame.f_locals.get("x") + list(frame.f_locals.values()) + + threading_helper.run_concurrently([dropper, reader, reader]) + + def test_gen_setitem_cell_old_value_destructor_stw(self): + # the old cell value must be released after the world restarts + deleted = [] + + def make_gen(): + x = None + def gen_fn(): + nonlocal x + yield x + return gen_fn() + + g = make_gen() + next(g) + frame = g.gi_frame + + class Old: + def __del__(self): + deleted.append(frame.f_locals.get("x")) + + frame.f_locals["x"] = Old() + frame.f_locals["x"] = "new" # replace cell value: destructor runs + self.assertEqual(deleted, ["new"]) + g.close() + + def test_gen_f_locals_key_runs_python_code(self): + # key's __hash__ and __eq__ must not run with the world stopped + class Key: + def __init__(self, value): + self.value = value + + def __hash__(self): + gc.collect() + return hash(self.value) + + def __eq__(self, other): + gc.collect() + if isinstance(other, Key): + other = other.value + return self.value == other + + def gen_fn(): + x = 1 + yield + + g = gen_fn() + next(g) + f_locals = g.gi_frame.f_locals + self.assertEqual(f_locals[Key("x")], 1) + self.assertIn(Key("x"), f_locals) + f_locals[Key("x")] = 2 + self.assertEqual(f_locals["x"], 2) + with self.assertRaises(ValueError): + f_locals.pop(Key("x")) + + self.assertNotIn(Key("extra"), f_locals) + f_locals[Key("extra")] = 3 + self.assertEqual(f_locals[Key("extra")], 3) + self.assertIn(Key("extra"), f_locals) + self.assertEqual(f_locals.pop(Key("extra")), 3) + with self.assertRaises(KeyError): + f_locals[Key("extra")] + g.close() + + def test_concurrent_f_locals_extra_iteration(self): + # iterate the extra locals while they are modified + frame = (lambda: sys._getframe())() + + def writer(): + for i in range(5000): + frame.f_locals[f"k{i % 32}"] = [i] + frame.f_locals.pop(f"k{i * 7 % 32}", None) + + def reader(): + for _ in range(2000): + f_locals = frame.f_locals + list(f_locals.keys()) + list(f_locals.values()) + list(f_locals.items()) + + threading_helper.run_concurrently([writer, writer, reader, reader]) + + def test_gen_getvar_while_running(self): + # PyFrame_GetVar() reads fast locals and must synchronize with + # the frame's owner as well. + _testcapi = import_helper.import_module("_testcapi") + for _ in range(5): + def gen_fn(): + obj = None + yield + for i in range(2000): + obj = [i] * 4 + yield obj + + g = gen_fn() + next(g) + frame = g.gi_frame + barrier = threading.Barrier(3) + + def runner(): + barrier.wait() + next(g) + + def reader(): + barrier.wait() + for _ in range(100): + try: + _testcapi.frame_getvar(frame, "obj") + except NameError: + pass + + threading_helper.run_concurrently([runner, reader, reader]) + g.close() + def test_concurrent_frame_clear(self): # Test race between frame.clear() and attribute reads. def create_frame(): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-08-28-10-15-00.gh-issue-144446.pQ7wXn.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-28-10-15-00.gh-issue-144446.pQ7wXn.rst new file mode 100644 index 00000000000000..2718a4cc7487f0 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-08-28-10-15-00.gh-issue-144446.pQ7wXn.rst @@ -0,0 +1,2 @@ +Fix thread safety of :attr:`frame.f_locals` and :c:func:`PyFrame_GetVar` on +frames executing on another thread in the free-threaded build. diff --git a/Objects/frameobject.c b/Objects/frameobject.c index 475be76dc3da21..415c194d2f2d83 100644 --- a/Objects/frameobject.c +++ b/Objects/frameobject.c @@ -14,6 +14,8 @@ #include "pycore_object.h" // _PyObject_GC_UNTRACK() #include "pycore_opcode_metadata.h" // _PyOpcode_Caches #include "pycore_optimizer.h" // _Py_Executors_InvalidateDependency() +#include "pycore_pystate.h" // _PyEval_StopTheWorld() +#include "pycore_tstate.h" // _PyThreadStateImpl #include "pycore_tuple.h" // _PyTuple_FromPair #include "pycore_unicodeobject.h" // _PyUnicode_Equal() #include "pycore_weakref.h" // FT_CLEAR_WEAKREFS() @@ -41,6 +43,80 @@ class frame "PyFrameObject *" "&PyFrame_Type" /*[clinic end generated code: output=da39a3ee5e6b4b0d input=2d1dbf2e06cf351f]*/ +#ifdef Py_GIL_DISABLED +// Returns 1 if the frame may be executing or resumed on another thread. +static int +_frame_is_on_other_thread(PyFrameObject *frame) +{ + _PyInterpreterFrame *iframe = frame->f_frame; + if (iframe->owner == FRAME_OWNED_BY_THREAD) { + PyThreadState *tstate = _PyThreadState_GET(); + int32_t our_tlbc = ((_PyThreadStateImpl *)tstate)->tlbc_index; + return iframe->tlbc_index != our_tlbc; + } + if (iframe->owner == FRAME_OWNED_BY_GENERATOR) { + // Another thread may be running or resume the generator. + return 1; + } + // FRAME_OWNED_BY_FRAME_OBJECT: the frame can no longer run. + return 0; +} +#endif + +// Evaluate CALL under the frame's critical section, or with the world +// stopped if the frame may be running on another thread. +#ifdef Py_GIL_DISABLED +#define FRAMELOCALSPROXY_LOCKED(FRAME, CALL, RESULT) \ + do { \ + int _stw; \ + Py_BEGIN_CRITICAL_SECTION(FRAME); \ + _stw = _frame_is_on_other_thread(FRAME); \ + if (!_stw) { \ + RESULT = CALL; \ + } \ + Py_END_CRITICAL_SECTION(); \ + if (_stw) { \ + PyInterpreterState *interp = _PyInterpreterState_GET(); \ + _PyEval_StopTheWorld(interp); \ + RESULT = CALL; \ + _PyEval_StartTheWorld(interp); \ + } \ + } while (0) +#else +#define FRAMELOCALSPROXY_LOCKED(FRAME, CALL, RESULT) \ + do { \ + RESULT = CALL; \ + } while (0) +#endif + + +// Returns a borrowed reference, the frame object keeps its code alive. +static PyCodeObject * +framelocalsproxy_getcode(PyFrameObject *frame) +{ + PyCodeObject *co; + Py_BEGIN_CRITICAL_SECTION(frame); + co = _PyFrame_GetCode(frame->f_frame); + Py_END_CRITICAL_SECTION(); + return co; +} + +// Returns a new reference to the extra locals dict or NULL. The running +// frame never touches it, so no stop the world is needed. +static PyObject * +framelocalsproxy_get_extra(PyFrameObject *frame, bool create) +{ + PyObject *extra; + Py_BEGIN_CRITICAL_SECTION(frame); + extra = frame->f_extra_locals; + if (extra == NULL && create) { + extra = frame->f_extra_locals = PyDict_New(); + } + Py_XINCREF(extra); + Py_END_CRITICAL_SECTION(); + return extra; +} + // Returns new reference or NULL static PyObject * framelocalsproxy_getval(_PyInterpreterFrame *frame, PyCodeObject *co, int i) @@ -127,7 +203,7 @@ framelocalsproxy_getkeyindex(PyFrameObject *frame, PyObject *key, bool read, PyO // value_ptr should only be given if we are reading the value assert(read || value_ptr == NULL); - PyCodeObject *co = _PyFrame_GetCode(frame->f_frame); + PyCodeObject *co = framelocalsproxy_getcode(frame); // Ensure that the key is hashable. Py_hash_t key_hash = PyObject_Hash(key); @@ -143,7 +219,9 @@ framelocalsproxy_getkeyindex(PyFrameObject *frame, PyObject *key, bool read, PyO PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i); if (name == key) { if (read) { - PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i); + PyObject *value; + FRAMELOCALSPROXY_LOCKED(frame, + framelocalsproxy_getval(frame->f_frame, co, i), value); if (value != NULL) { if (value_ptr != NULL) { *value_ptr = value; @@ -181,7 +259,9 @@ framelocalsproxy_getkeyindex(PyFrameObject *frame, PyObject *key, bool read, PyO } if (same) { if (read) { - PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i); + PyObject *value; + FRAMELOCALSPROXY_LOCKED(frame, + framelocalsproxy_getval(frame->f_frame, co, i), value); if (value != NULL) { if (value_ptr != NULL) { *value_ptr = value; @@ -220,12 +300,11 @@ framelocalsproxy_getitem(PyObject *self, PyObject *key) // Okay not in the fast locals, try extra locals - PyObject *extra = frame->f_extra_locals; + PyObject *extra = framelocalsproxy_get_extra(frame, false); if (extra != NULL) { - if (PyDict_GetItemRef(extra, key, &value) < 0) { - return NULL; - } - if (value != NULL) { + int found = PyDict_GetItemRef(extra, key, &value); + Py_DECREF(extra); + if (found != 0) { return value; } } @@ -261,14 +340,55 @@ add_overwritten_fast_local(PyFrameObject *frame, PyObject *obj) return 0; } +// The replaced value is returned in `*old_value` so that it is decref'd +// outside stop the world. static int -framelocalsproxy_setitem(PyObject *self, PyObject *key, PyObject *value) +framelocalsproxy_setfast_lock_held(PyFrameObject *frame, int i, + PyObject *value, PyObject **old_value) { /* Merge locals into fast locals */ - PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame; _PyStackRef *fast = _PyFrame_GetLocalsArray(frame->f_frame); PyCodeObject *co = _PyFrame_GetCode(frame->f_frame); +#if _Py_TIER2 + _Py_Executors_InvalidateDependency(_PyInterpreterState_GET(), co, 1); +#endif + + _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i); + _PyStackRef oldvalue = fast[i]; + PyObject *cell = NULL; + if (kind == CO_FAST_FREE) { + // The cell was set when the frame was created from + // the function's closure. + assert(!PyStackRef_IsNull(oldvalue) && PyCell_Check(PyStackRef_AsPyObjectBorrow(oldvalue))); + cell = PyStackRef_AsPyObjectBorrow(oldvalue); + } else if (kind & CO_FAST_CELL && !PyStackRef_IsNull(oldvalue)) { + PyObject *as_obj = PyStackRef_AsPyObjectBorrow(oldvalue); + if (PyCell_Check(as_obj)) { + cell = as_obj; + } + } + if (cell != NULL) { + Py_XINCREF(value); + *old_value = PyCell_SwapTakeRef((PyCellObject *)cell, value); + } else if (value != PyStackRef_AsPyObjectBorrow(oldvalue)) { + PyObject *old_obj = PyStackRef_AsPyObjectBorrow(fast[i]); + if (old_obj != NULL && !_Py_IsImmortal(old_obj)) { + if (add_overwritten_fast_local(frame, old_obj) < 0) { + return -1; + } + PyStackRef_CLOSE(fast[i]); + } + fast[i] = PyStackRef_FromPyObjectNew(value); + } + return 0; +} + +static int +framelocalsproxy_setitem(PyObject *self, PyObject *key, PyObject *value) +{ + PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame; + int i = framelocalsproxy_getkeyindex(frame, key, false, NULL); if (i == -2) { return -1; @@ -278,64 +398,33 @@ framelocalsproxy_setitem(PyObject *self, PyObject *key, PyObject *value) PyErr_SetString(PyExc_ValueError, "cannot remove local variables from FrameLocalsProxy"); return -1; } - -#if _Py_TIER2 - _Py_Executors_InvalidateDependency(_PyInterpreterState_GET(), co, 1); -#endif - - _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i); - _PyStackRef oldvalue = fast[i]; - PyObject *cell = NULL; - if (kind == CO_FAST_FREE) { - // The cell was set when the frame was created from - // the function's closure. - assert(!PyStackRef_IsNull(oldvalue) && PyCell_Check(PyStackRef_AsPyObjectBorrow(oldvalue))); - cell = PyStackRef_AsPyObjectBorrow(oldvalue); - } else if (kind & CO_FAST_CELL && !PyStackRef_IsNull(oldvalue)) { - PyObject *as_obj = PyStackRef_AsPyObjectBorrow(oldvalue); - if (PyCell_Check(as_obj)) { - cell = as_obj; - } - } - if (cell != NULL) { - Py_XINCREF(value); - PyCell_SetTakeRef((PyCellObject *)cell, value); - } else if (value != PyStackRef_AsPyObjectBorrow(oldvalue)) { - PyObject *old_obj = PyStackRef_AsPyObjectBorrow(fast[i]); - if (old_obj != NULL && !_Py_IsImmortal(old_obj)) { - if (add_overwritten_fast_local(frame, old_obj) < 0) { - return -1; - } - PyStackRef_CLOSE(fast[i]); - } - fast[i] = PyStackRef_FromPyObjectNew(value); - } - return 0; + PyObject *old_value = NULL; + int result; + FRAMELOCALSPROXY_LOCKED(frame, + framelocalsproxy_setfast_lock_held(frame, i, value, &old_value), + result); + Py_XDECREF(old_value); + return result; } // Okay not in the fast locals, try extra locals - PyObject *extra = frame->f_extra_locals; - + PyObject *extra = framelocalsproxy_get_extra(frame, value != NULL); if (extra == NULL) { if (value == NULL) { _PyErr_SetKeyError(key); - return -1; } - extra = PyDict_New(); - if (extra == NULL) { - return -1; - } - frame->f_extra_locals = extra; + return -1; } - assert(PyDict_Check(extra)); - + int result; if (value == NULL) { - return PyDict_DelItem(extra, key); + result = PyDict_DelItem(extra, key); } else { - return PyDict_SetItem(extra, key, value); + result = PyDict_SetItem(extra, key, value); } + Py_DECREF(extra); + return result; } static int @@ -388,9 +477,8 @@ framelocalsproxy_merge(PyObject* self, PyObject* other) } static PyObject * -framelocalsproxy_keys(PyObject *self, PyObject *Py_UNUSED(ignored)) +framelocalsproxy_keys_lock_held(PyFrameObject *frame) { - PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame; PyCodeObject *co = _PyFrame_GetCode(frame->f_frame); PyObject *names = PyList_New(0); if (names == NULL) { @@ -426,13 +514,20 @@ framelocalsproxy_keys(PyObject *self, PyObject *Py_UNUSED(ignored)) Py_ssize_t i = 0; PyObject *key = NULL; PyObject *value = NULL; + int err = 0; + Py_BEGIN_CRITICAL_SECTION(frame->f_extra_locals); while (PyDict_Next(frame->f_extra_locals, &i, &key, &value)) { if (PyList_Append(names, key) < 0) { - Py_DECREF(names); - return NULL; + err = -1; + break; } } + Py_END_CRITICAL_SECTION(); + if (err < 0) { + Py_DECREF(names); + return NULL; + } } return names; @@ -443,6 +538,16 @@ framelocalsproxy_keys(PyObject *self, PyObject *Py_UNUSED(ignored)) return NULL; } +static PyObject * +framelocalsproxy_keys(PyObject *self, PyObject *Py_UNUSED(ignored)) +{ + PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame; + PyObject *result; + FRAMELOCALSPROXY_LOCKED(frame, + framelocalsproxy_keys_lock_held(frame), result); + return result; +} + static void framelocalsproxy_dealloc(PyObject *self) { @@ -614,9 +719,8 @@ framelocalsproxy_inplace_or(PyObject *self, PyObject *other) } static PyObject * -framelocalsproxy_values(PyObject *self, PyObject *Py_UNUSED(ignored)) +framelocalsproxy_values_lock_held(PyFrameObject *frame) { - PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame; PyCodeObject *co = _PyFrame_GetCode(frame->f_frame); PyObject *values = PyList_New(0); if (values == NULL) { @@ -652,12 +756,19 @@ framelocalsproxy_values(PyObject *self, PyObject *Py_UNUSED(ignored)) Py_ssize_t j = 0; PyObject *key = NULL; PyObject *value = NULL; + int err = 0; + Py_BEGIN_CRITICAL_SECTION(frame->f_extra_locals); while (PyDict_Next(frame->f_extra_locals, &j, &key, &value)) { if (PyList_Append(values, value) < 0) { - Py_DECREF(values); - return NULL; + err = -1; + break; } } + Py_END_CRITICAL_SECTION(); + if (err < 0) { + Py_DECREF(values); + return NULL; + } } return values; @@ -669,9 +780,18 @@ framelocalsproxy_values(PyObject *self, PyObject *Py_UNUSED(ignored)) } static PyObject * -framelocalsproxy_items(PyObject *self, PyObject *Py_UNUSED(ignored)) +framelocalsproxy_values(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame; + PyObject *result; + FRAMELOCALSPROXY_LOCKED(frame, + framelocalsproxy_values_lock_held(frame), result); + return result; +} + +static PyObject * +framelocalsproxy_items_lock_held(PyFrameObject *frame) +{ PyCodeObject *co = _PyFrame_GetCode(frame->f_frame); PyObject *items = PyList_New(0); if (items == NULL) { @@ -714,16 +834,21 @@ framelocalsproxy_items(PyObject *self, PyObject *Py_UNUSED(ignored)) Py_ssize_t j = 0; PyObject *key = NULL; PyObject *value = NULL; + int err = 0; + Py_BEGIN_CRITICAL_SECTION(frame->f_extra_locals); while (PyDict_Next(frame->f_extra_locals, &j, &key, &value)) { PyObject *pair = _PyTuple_FromPair(key, value); - if (pair == NULL) { - goto error; - } - - if (_PyList_AppendTakeRef((PyListObject *)items, pair) < 0) { - goto error; + if (pair == NULL + || _PyList_AppendTakeRef((PyListObject *)items, pair) < 0) + { + err = -1; + break; } } + Py_END_CRITICAL_SECTION(); + if (err < 0) { + goto error; + } } return items; @@ -734,10 +859,19 @@ framelocalsproxy_items(PyObject *self, PyObject *Py_UNUSED(ignored)) return NULL; } -static Py_ssize_t -framelocalsproxy_length(PyObject *self) +static PyObject * +framelocalsproxy_items(PyObject *self, PyObject *Py_UNUSED(ignored)) { PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame; + PyObject *result; + FRAMELOCALSPROXY_LOCKED(frame, + framelocalsproxy_items_lock_held(frame), result); + return result; +} + +static Py_ssize_t +framelocalsproxy_length_lock_held(PyFrameObject *frame) +{ PyCodeObject *co = _PyFrame_GetCode(frame->f_frame); Py_ssize_t size = 0; @@ -767,6 +901,16 @@ framelocalsproxy_length(PyObject *self) return size; } +static Py_ssize_t +framelocalsproxy_length(PyObject *self) +{ + PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame; + Py_ssize_t result; + FRAMELOCALSPROXY_LOCKED(frame, + framelocalsproxy_length_lock_held(frame), result); + return result; +} + static int framelocalsproxy_contains(PyObject *self, PyObject *key) { @@ -780,9 +924,11 @@ framelocalsproxy_contains(PyObject *self, PyObject *key) return 1; } - PyObject *extra = frame->f_extra_locals; + PyObject *extra = framelocalsproxy_get_extra(frame, false); if (extra != NULL) { - return PyDict_Contains(extra, key); + int result = PyDict_Contains(extra, key); + Py_DECREF(extra); + return result; } return 0; @@ -895,7 +1041,8 @@ framelocalsproxy_pop(PyObject* self, PyObject *const *args, Py_ssize_t nargs) PyObject *result = NULL; - if (frame->f_extra_locals == NULL) { + PyObject *extra = framelocalsproxy_get_extra(frame, false); + if (extra == NULL) { if (default_value != NULL) { return Py_XNewRef(default_value); } else { @@ -904,7 +1051,9 @@ framelocalsproxy_pop(PyObject* self, PyObject *const *args, Py_ssize_t nargs) } } - if (PyDict_Pop(frame->f_extra_locals, key, &result) < 0) { + int found = PyDict_Pop(extra, key, &result); + Py_DECREF(extra); + if (found < 0) { return NULL; } @@ -2426,15 +2575,11 @@ _PyFrame_GetLocals(_PyInterpreterFrame *frame) } -PyObject * -PyFrame_GetVar(PyFrameObject *frame_obj, PyObject *name) +// Returns 1 if `name` is a bound fast local, storing its value in `*pvalue`. +static int +frame_getvar_lock_held(PyFrameObject *frame_obj, PyObject *name, + PyObject **pvalue) { - if (!PyUnicode_Check(name)) { - PyErr_Format(PyExc_TypeError, "name must be str, not %s", - Py_TYPE(name)->tp_name); - return NULL; - } - _PyInterpreterFrame *frame = frame_obj->f_frame; frame_init_get_vars(frame); @@ -2444,17 +2589,30 @@ PyFrame_GetVar(PyFrameObject *frame_obj, PyObject *name) if (!_PyUnicode_Equal(var_name, name)) { continue; } - - PyObject *value; - if (!frame_get_var(frame, co, i, &value)) { - break; - } - if (value == NULL) { - break; + if (!frame_get_var(frame, co, i, pvalue)) { + return 0; } - return value; + return *pvalue != NULL; + } + return 0; +} + +PyObject * +PyFrame_GetVar(PyFrameObject *frame_obj, PyObject *name) +{ + if (!PyUnicode_Check(name)) { + PyErr_Format(PyExc_TypeError, "name must be str, not %s", + Py_TYPE(name)->tp_name); + return NULL; } + PyObject *value = NULL; + int found; + FRAMELOCALSPROXY_LOCKED(frame_obj, + frame_getvar_lock_held(frame_obj, name, &value), found); + if (found) { + return value; + } PyErr_Format(PyExc_NameError, "variable %R does not exist", name); return NULL; }