gh-155742: Check singletons consistencty in the garbage collector - #155801
gh-155742: Check singletons consistencty in the garbage collector#155801vstinner wants to merge 5 commits into
Conversation
If Python is built in debug mode or with assertions, the garbage collector now checks singletons consistencty to detect data corruption in C extension. Add _Py_CheckSingletons() function. Call this function on a GC collection. Add tests checking that corrupting a singleton is properly detected.
|
This check should detect data corruption such as issue gh-155702. |
Fix also a compiler warning on Windows:
Objects\object.c(3629,39): warning C4244: 'function': conversion
from 'long' to 'un signed char', possible loss of data
|
The check is run on a garbage collection, since it's easy to add there: the GC is collected infrequently, so the overhead should be limited. These checks are part of a long series of changes to detect data corruptions earlier and (if possible) in a reliable way in C extensions:
|
|
I ran a quick benchmark: import pyperf
import gc
import ctypes.util
runner = pyperf.Runner()
@ctypes.util.wrap_dll_function(ctypes.pythonapi)
def _Py_CheckSingletons() -> None:
pass
runner.bench_func('gc.collect', gc.collect)
runner.bench_func('_Py_CheckSingletons', _Py_CheckSingletons)With this change: diff --git a/Objects/object.c b/Objects/object.c
index 0837b8e81d7..657d180a53f 100644
--- a/Objects/object.c
+++ b/Objects/object.c
@@ -3595,6 +3595,9 @@ check_singleton_unicode(PyObject *obj, Py_ssize_t length, Py_UCS4 ch)
//
// Since the hash is computed lazily, don't check the hash, except for empty
// tuple.
+
+PyAPI_FUNC(void) _Py_CheckSingletons(void);
+
void
_Py_CheckSingletons(void)
{I ran the benchmark on Fedora 44 with Python built in debug mode ( Results without the change (_Py_CheckSingletons is missing, it only exists in the PR): Results with the change: This change makes |
If Python is built in debug mode or with assertions, the garbage collector now checks singletons consistencty to detect data corruption in C extension.
Add _Py_CheckSingletons() function. Call this function on a GC collection. Add tests checking that corrupting a singleton is properly detected.