Skip to content

Commit b6e45cc

Browse files
committed
gh-162529: Run function watchers under the function's critical section
This ensures that function events arrive in the same order as their corresponding stores, and a watcher can read the function's fields without racing other setters (provided the watcher callback doesn't block and suspend the critical section). An alternative would be to call the callback with the world stopped, but that's dangerous. The callback could inadvertently re-enter Python code and deadlock trying to stop the world again (e.g. triggering GC). This is a behavior difference for users of function watchers on free-threaded builds of CPython. It has no effect on users of the default build.
1 parent 22691a3 commit b6e45cc

4 files changed

Lines changed: 252 additions & 41 deletions

File tree

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import gc
2+
import unittest
3+
4+
from test.support import import_helper, threading_helper
5+
6+
_testcapi = import_helper.import_module("_testcapi")
7+
8+
NTHREADS = 8
9+
ITERS = 200
10+
11+
12+
def template(x=1, *, y=2):
13+
return x
14+
15+
16+
@threading_helper.requires_working_threading()
17+
class TestFuncWatcherThreadSafety(unittest.TestCase):
18+
"""MODIFY events and stores to function fields must not interleave.
19+
20+
When a function watcher receives a MODIFY event, the function must still
21+
hold the value announced by the previous event for the same attribute.
22+
Otherwise watchers that track a function's state (e.g. a JIT) can end up
23+
believing it holds a different value than it does.
24+
"""
25+
26+
def setUp(self):
27+
# Stopping the world for a garbage collection can suspend the
28+
# function's critical section between an event and its store. Keep
29+
# the GC out of the way so this checks what the setters guarantee.
30+
if gc.isenabled():
31+
gc.disable()
32+
self.addCleanup(gc.enable)
33+
34+
def check_events_match_stores(self, event, getter, setter, make_value):
35+
def target(x=1, *, y=2):
36+
return x
37+
38+
def writer():
39+
for _ in range(ITERS):
40+
setter(target, make_value())
41+
42+
_testcapi.start_func_order_watcher(target, event)
43+
try:
44+
threading_helper.run_concurrently(writer, NTHREADS)
45+
finally:
46+
history, mismatches = _testcapi.stop_func_order_watcher()
47+
48+
self.assertEqual(mismatches, 0,
49+
f"{mismatches} of {len(history) - 1} events were "
50+
f"delivered before the previous event's store")
51+
self.assertEqual(len(history), NTHREADS * ITERS + 1)
52+
self.assertIs(getter(target), history[-1])
53+
54+
def check_attr(self, attr, event, make_value):
55+
self.check_events_match_stores(
56+
event,
57+
lambda f: getattr(f, attr),
58+
lambda f, v: setattr(f, attr, v),
59+
make_value)
60+
61+
def test_code(self):
62+
# Every store gets a distinct code object so that identity checks
63+
# can't pass by coincidence.
64+
code = template.__code__
65+
self.check_attr(
66+
"__code__", _testcapi.PYFUNC_EVENT_MODIFY_CODE,
67+
lambda: code.replace(co_name=f"template_{id(object())}"))
68+
69+
def test_defaults(self):
70+
self.check_attr(
71+
"__defaults__", _testcapi.PYFUNC_EVENT_MODIFY_DEFAULTS,
72+
lambda: (object(),))
73+
74+
def test_kwdefaults(self):
75+
self.check_attr(
76+
"__kwdefaults__", _testcapi.PYFUNC_EVENT_MODIFY_KWDEFAULTS,
77+
lambda: {"y": object()})
78+
79+
def test_qualname(self):
80+
self.check_attr(
81+
"__qualname__", _testcapi.PYFUNC_EVENT_MODIFY_QUALNAME,
82+
lambda: str(object()))
83+
84+
def test_defaults_via_capi(self):
85+
self.check_events_match_stores(
86+
_testcapi.PYFUNC_EVENT_MODIFY_DEFAULTS,
87+
lambda f: f.__defaults__,
88+
_testcapi.set_func_defaults_via_capi,
89+
lambda: (object(),))
90+
91+
def test_kwdefaults_via_capi(self):
92+
self.check_events_match_stores(
93+
_testcapi.PYFUNC_EVENT_MODIFY_KWDEFAULTS,
94+
lambda f: f.__kwdefaults__,
95+
_testcapi.set_func_kwdefaults_via_capi,
96+
lambda: {"y": object()})
97+
98+
99+
if __name__ == "__main__":
100+
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Function watchers are now run under the function's critical section.

‎Modules/_testcapi/watchers.c‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include "pycore_interp_structs.h" // CODE_MAX_WATCHERS
1111
#include "pycore_context.h" // CONTEXT_MAX_WATCHERS
1212
#include "pycore_lock.h" // _PyOnceFlag
13+
#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_PTR_RELAXED()
1314

1415
/*[clinic input]
1516
module _testcapi
@@ -648,6 +649,117 @@ allocate_too_many_func_watchers(PyObject *self, PyObject *args)
648649
Py_RETURN_NONE;
649650
}
650651

652+
// A function watcher that checks MODIFY events for one function will arrive in
653+
// the same order as their corresponding stores. When an event is delivered,
654+
// the watched field must still hold the value announced by the previous event.
655+
// Written in C so that it doesn't run any bytecode or drop references to
656+
// objects owned by other threads, either of which can block and suspend the
657+
// function's critical section.
658+
static int order_watcher_id = -1;
659+
static PyObject *order_target;
660+
static PyFunction_WatchEvent order_event;
661+
static PyObject *order_history; // announced values, in event order
662+
static Py_ssize_t order_mismatches;
663+
664+
static PyObject *
665+
get_watched_func_field(PyFunctionObject *func, PyFunction_WatchEvent event)
666+
{
667+
PyObject *value;
668+
switch (event) {
669+
case PyFunction_EVENT_MODIFY_CODE:
670+
value = FT_ATOMIC_LOAD_PTR_RELAXED(func->func_code);
671+
break;
672+
case PyFunction_EVENT_MODIFY_DEFAULTS:
673+
value = FT_ATOMIC_LOAD_PTR_RELAXED(func->func_defaults);
674+
break;
675+
case PyFunction_EVENT_MODIFY_KWDEFAULTS:
676+
value = FT_ATOMIC_LOAD_PTR_RELAXED(func->func_kwdefaults);
677+
break;
678+
case PyFunction_EVENT_MODIFY_QUALNAME:
679+
value = FT_ATOMIC_LOAD_PTR_RELAXED(func->func_qualname);
680+
break;
681+
default:
682+
Py_UNREACHABLE();
683+
}
684+
return value == NULL ? Py_None : value;
685+
}
686+
687+
static int
688+
order_func_watcher_callback(PyFunction_WatchEvent event,
689+
PyFunctionObject *func, PyObject *new_value)
690+
{
691+
if ((PyObject *)func != order_target || event != order_event) {
692+
return 0;
693+
}
694+
PyObject *current = get_watched_func_field(func, event);
695+
int res;
696+
Py_BEGIN_CRITICAL_SECTION(order_history);
697+
Py_ssize_t n = PyList_GET_SIZE(order_history);
698+
if (PyList_GET_ITEM(order_history, n - 1) != current) {
699+
_Py_atomic_add_ssize(&order_mismatches, 1);
700+
}
701+
res = PyList_Append(order_history, new_value ? new_value : Py_None);
702+
Py_END_CRITICAL_SECTION();
703+
return res;
704+
}
705+
706+
static PyObject *
707+
start_func_order_watcher(PyObject *self, PyObject *args)
708+
{
709+
PyObject *func;
710+
int event;
711+
if (!PyArg_ParseTuple(args, "O!i", &PyFunction_Type, &func, &event)) {
712+
return NULL;
713+
}
714+
if (event != PyFunction_EVENT_MODIFY_CODE &&
715+
event != PyFunction_EVENT_MODIFY_DEFAULTS &&
716+
event != PyFunction_EVENT_MODIFY_KWDEFAULTS &&
717+
event != PyFunction_EVENT_MODIFY_QUALNAME)
718+
{
719+
PyErr_SetString(PyExc_ValueError, "expected a MODIFY event");
720+
return NULL;
721+
}
722+
if (order_watcher_id != -1) {
723+
PyErr_SetString(PyExc_RuntimeError, "order watcher already active");
724+
return NULL;
725+
}
726+
PyObject *current = get_watched_func_field((PyFunctionObject *)func,
727+
(PyFunction_WatchEvent)event);
728+
PyObject *history = PyList_New(1);
729+
if (history == NULL) {
730+
return NULL;
731+
}
732+
PyList_SET_ITEM(history, 0, Py_NewRef(current));
733+
int wid = PyFunction_AddWatcher(order_func_watcher_callback);
734+
if (wid < 0) {
735+
Py_DECREF(history);
736+
return NULL;
737+
}
738+
order_watcher_id = wid;
739+
order_target = Py_NewRef(func);
740+
order_event = (PyFunction_WatchEvent)event;
741+
order_history = history;
742+
order_mismatches = 0;
743+
Py_RETURN_NONE;
744+
}
745+
746+
static PyObject *
747+
stop_func_order_watcher(PyObject *self, PyObject *Py_UNUSED(args))
748+
{
749+
if (order_watcher_id == -1) {
750+
PyErr_SetString(PyExc_RuntimeError, "order watcher not active");
751+
return NULL;
752+
}
753+
if (PyFunction_ClearWatcher(order_watcher_id) < 0) {
754+
return NULL;
755+
}
756+
order_watcher_id = -1;
757+
PyObject *result = Py_BuildValue("(Nn)", order_history, order_mismatches);
758+
order_history = NULL;
759+
Py_CLEAR(order_target);
760+
return result;
761+
}
762+
651763
// Test contexct object watchers
652764
#define NUM_CONTEXT_WATCHERS 2
653765
static int context_watcher_ids[NUM_CONTEXT_WATCHERS] = {-1, -1};
@@ -861,6 +973,8 @@ static PyMethodDef test_methods[] = {
861973
_TESTCAPI_SET_FUNC_KWDEFAULTS_VIA_CAPI_METHODDEF
862974
{"allocate_too_many_func_watchers", allocate_too_many_func_watchers,
863975
METH_NOARGS, NULL},
976+
{"start_func_order_watcher", start_func_order_watcher, METH_VARARGS, NULL},
977+
{"stop_func_order_watcher", stop_func_order_watcher, METH_NOARGS, NULL},
864978

865979
// Code object watchers.
866980
{"add_context_watcher", add_context_watcher, METH_O, NULL},

‎Objects/funcobject.c‎

Lines changed: 37 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,32 @@ func_clear_version(PyInterpreterState *interp, PyFunctionObject *func)
350350
func->func_version = FUNC_VERSION_CLEARED;
351351
}
352352

353+
/* Notify watchers that *field is about to change, then store new_value (a new
354+
reference) into it.
355+
356+
The function's critical section is held across both steps so that concurrent
357+
modifications of the same function deliver their events in the same order as
358+
their stores. The watchers must not be called while the world is stopped as
359+
they can run arbitrary code and can deadlock by stopping the world again
360+
(e.g. by triggering a garbage collection) or by waiting on a lock held by a
361+
parked thread. */
362+
static void
363+
func_set_watched_field(PyFunctionObject *func, PyFunction_WatchEvent event,
364+
PyObject **field, PyObject *new_value)
365+
{
366+
PyInterpreterState *interp = _PyInterpreterState_GET();
367+
PyObject *old_value;
368+
Py_BEGIN_CRITICAL_SECTION(func);
369+
handle_func_event(event, func, new_value);
370+
_PyEval_StopTheWorld(interp);
371+
func_clear_version(interp, func);
372+
old_value = *field;
373+
*field = new_value;
374+
_PyEval_StartTheWorld(interp);
375+
Py_END_CRITICAL_SECTION();
376+
Py_XDECREF(old_value);
377+
}
378+
353379
void
354380
_PyFunction_ClearCodeByVersion(uint32_t version)
355381
{
@@ -436,14 +462,8 @@ PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
436462
return -1;
437463
}
438464
PyFunctionObject *func = (PyFunctionObject *)op;
439-
handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, func, defaults);
440-
PyInterpreterState *interp = _PyInterpreterState_GET();
441-
_PyEval_StopTheWorld(interp);
442-
func_clear_version(interp, func);
443-
PyObject *old_defaults = func->func_defaults;
444-
func->func_defaults = defaults;
445-
_PyEval_StartTheWorld(interp);
446-
Py_XDECREF(old_defaults);
465+
func_set_watched_field(func, PyFunction_EVENT_MODIFY_DEFAULTS,
466+
&func->func_defaults, defaults);
447467
return 0;
448468
}
449469

@@ -486,14 +506,8 @@ PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
486506
return -1;
487507
}
488508
PyFunctionObject *func = (PyFunctionObject *)op;
489-
handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, func, defaults);
490-
PyInterpreterState *interp = _PyInterpreterState_GET();
491-
_PyEval_StopTheWorld(interp);
492-
func_clear_version(interp, func);
493-
PyObject *old_kwdefaults = func->func_kwdefaults;
494-
func->func_kwdefaults = defaults;
495-
_PyEval_StartTheWorld(interp);
496-
Py_XDECREF(old_kwdefaults);
509+
func_set_watched_field(func, PyFunction_EVENT_MODIFY_KWDEFAULTS,
510+
&func->func_kwdefaults, defaults);
497511
return 0;
498512
}
499513

@@ -731,14 +745,8 @@ func_set_code(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
731745
}
732746
}
733747

734-
handle_func_event(PyFunction_EVENT_MODIFY_CODE, op, value);
735-
PyInterpreterState *interp = _PyInterpreterState_GET();
736-
_PyEval_StopTheWorld(interp);
737-
func_clear_version(interp, op);
738-
PyObject *old_code = op->func_code;
739-
op->func_code = Py_NewRef(value);
740-
_PyEval_StartTheWorld(interp);
741-
Py_XDECREF(old_code);
748+
func_set_watched_field(op, PyFunction_EVENT_MODIFY_CODE,
749+
&op->func_code, Py_NewRef(value));
742750
return 0;
743751
}
744752

@@ -786,8 +794,8 @@ func_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
786794
"__qualname__ must be set to a string object");
787795
return -1;
788796
}
789-
handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, (PyFunctionObject *) op, value);
790797
Py_BEGIN_CRITICAL_SECTION(op);
798+
handle_func_event(PyFunction_EVENT_MODIFY_QUALNAME, op, value);
791799
_PyObject_XSetRefDelayed(&op->func_qualname, Py_NewRef(value));
792800
Py_END_CRITICAL_SECTION();
793801
return 0;
@@ -873,14 +881,8 @@ func_set_defaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
873881
return -1;
874882
}
875883

876-
handle_func_event(PyFunction_EVENT_MODIFY_DEFAULTS, op, value);
877-
PyInterpreterState *interp = _PyInterpreterState_GET();
878-
_PyEval_StopTheWorld(interp);
879-
func_clear_version(interp, op);
880-
PyObject *old_defaults = op->func_defaults;
881-
op->func_defaults = Py_XNewRef(value);
882-
_PyEval_StartTheWorld(interp);
883-
Py_XDECREF(old_defaults);
884+
func_set_watched_field(op, PyFunction_EVENT_MODIFY_DEFAULTS,
885+
&op->func_defaults, Py_XNewRef(value));
884886
return 0;
885887
}
886888

@@ -921,14 +923,8 @@ func_set_kwdefaults(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
921923
return -1;
922924
}
923925

924-
handle_func_event(PyFunction_EVENT_MODIFY_KWDEFAULTS, op, value);
925-
PyInterpreterState *interp = _PyInterpreterState_GET();
926-
_PyEval_StopTheWorld(interp);
927-
func_clear_version(interp, op);
928-
PyObject *old_kwdefaults = op->func_kwdefaults;
929-
op->func_kwdefaults = Py_XNewRef(value);
930-
_PyEval_StartTheWorld(interp);
931-
Py_XDECREF(old_kwdefaults);
926+
func_set_watched_field(op, PyFunction_EVENT_MODIFY_KWDEFAULTS,
927+
&op->func_kwdefaults, Py_XNewRef(value));
932928
return 0;
933929
}
934930

0 commit comments

Comments
 (0)