From 19755e18457bc8f16e119bc5366a2f8632ff647c Mon Sep 17 00:00:00 2001 From: Eric Snow Date: Fri, 14 Jun 2024 16:05:51 -0600 Subject: Avoid a race on _PyRuntime.types.managed_static.types[i].interp_count. Closes: https://github.com/python/cpython/pull/120529 --- Include/internal/pycore_typeobject.h | 1 + Objects/typeobject.c | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/Include/internal/pycore_typeobject.h b/Include/internal/pycore_typeobject.h index 05f125f928c..e1d9e109f77 100644 --- a/Include/internal/pycore_typeobject.h +++ b/Include/internal/pycore_typeobject.h @@ -31,6 +31,7 @@ struct _types_runtime_state { unsigned int next_version_tag; struct { + PyMutex mutex; struct { PyTypeObject *type; int64_t interp_count; diff --git a/Objects/typeobject.c b/Objects/typeobject.c index f55b77a6e54..44ca7211fba 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -244,9 +244,11 @@ managed_static_type_state_init(PyInterpreterState *interp, PyTypeObject *self, ? index : index + _Py_MAX_MANAGED_STATIC_BUILTIN_TYPES; + PyMutex_Lock(&_PyRuntime.types.managed_static.mutex); assert((initial == 1) == (_PyRuntime.types.managed_static.types[full_index].interp_count == 0)); _PyRuntime.types.managed_static.types[full_index].interp_count += 1; + PyMutex_Unlock(&_PyRuntime.types.managed_static.mutex); if (initial) { assert(_PyRuntime.types.managed_static.types[full_index].type == NULL); @@ -300,7 +302,9 @@ managed_static_type_state_clear(PyInterpreterState *interp, PyTypeObject *self, state->type = NULL; assert(state->tp_weaklist == NULL); // It was already cleared out. + PyMutex_Lock(&_PyRuntime.types.managed_static.mutex); _PyRuntime.types.managed_static.types[full_index].interp_count -= 1; + PyMutex_Unlock(&_PyRuntime.types.managed_static.mutex); if (final) { assert(!_PyRuntime.types.managed_static.types[full_index].interp_count); _PyRuntime.types.managed_static.types[full_index].type = NULL; -- cgit v1.2.3-65-gdbad