Skip to content

gh-135380: enhance critical section held assertions #135381

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion Include/internal/pycore_critical_section.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ extern "C" {

# define _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op) \
if (Py_REFCNT(op) != 1) { \
Copy link
Member

@vstinner vstinner Jun 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense / would it be possible to move the REFCNT test inside _PyCriticalSection_AssertHeldObj() to make this macro a no-op when built in release mode without assertions?

_Py_CRITICAL_SECTION_ASSERT_MUTEX_LOCKED(&_PyObject_CAST(op)->ob_mutex); \
_PyCriticalSection_AssertHeldObj(_PyObject_CAST(op)); \
}

#else /* Py_DEBUG */
Expand Down Expand Up @@ -239,6 +239,28 @@ _PyCriticalSection_AssertHeld(PyMutex *mutex)
#endif
}

static inline void
_PyCriticalSection_AssertHeldObj(PyObject *op)
{
#ifdef Py_DEBUG
PyMutex *mutex = &_PyObject_CAST(op)->ob_mutex;
PyThreadState *tstate = _PyThreadState_GET();
uintptr_t prev = tstate->critical_section;
if (prev & _Py_CRITICAL_SECTION_TWO_MUTEXES) {
PyCriticalSection2 *cs = (PyCriticalSection2 *)(prev & ~_Py_CRITICAL_SECTION_MASK);
_PyObject_ASSERT_WITH_MSG(op,
(cs != NULL && (cs->_cs_base._cs_mutex == mutex || cs->_cs_mutex2 == mutex)),
"Critical section of object is not held");
}
else {
PyCriticalSection *cs = (PyCriticalSection *)(prev & ~_Py_CRITICAL_SECTION_MASK);
_PyObject_ASSERT_WITH_MSG(op,
(cs != NULL && cs->_cs_mutex == mutex),
"Critical section of object is not held");
}

#endif
}
#endif /* Py_GIL_DISABLED */

#ifdef __cplusplus
Expand Down
Loading