Fail if PyMem_Malloc() is called without holding the GIL · pythoncapi/cpython@ad52437 · GitHub
Skip to content

Commit ad52437

Browse files
committed
Fail if PyMem_Malloc() is called without holding the GIL
Issue python#26563: Debug hooks on Python memory allocators now raise a fatal error if functions of the PyMem_Malloc() family are called without holding the GIL.
1 parent 013024e commit ad52437

4 files changed

Lines changed: 43 additions & 11 deletions

File tree

Lib/test/test_capi.py

Lines changed: 13 additions & 4 deletions

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ Release date: tba
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #26563: Debug hooks on Python memory allocators now raise a fatal
14+
error if functions of the :c:func:`PyMem_Malloc` family are called without
15+
holding the GIL.
16+
1317
- Issue #26564: On error, the debug hooks on Python memory allocators now use
1418
the :mod:`tracemalloc` module to get the traceback where a memory block was
1519
allocated.

Modules/_testcapimodule.c

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3643,11 +3643,29 @@ pymem_api_misuse(PyObject *self, PyObject *args)
36433643
Py_RETURN_NONE;
36443644
}
36453645

3646+
static PyObject*
3647+
pymem_malloc_without_gil(PyObject *self, PyObject *args)
3648+
{
3649+
char *buffer;
3650+
3651+
/* Deliberate bug to test debug hooks on Python memory allocators:
3652+
call PyMem_Malloc() without holding the GIL */
3653+
Py_BEGIN_ALLOW_THREADS
3654+
buffer = PyMem_Malloc(10);
3655+
Py_END_ALLOW_THREADS
3656+
3657+
PyMem_Free(buffer);
3658+
3659+
Py_RETURN_NONE;
3660+
}
3661+
36463662
static PyObject*
36473663
pyobject_malloc_without_gil(PyObject *self, PyObject *args)
36483664
{
36493665
char *buffer;
36503666

3667+
/* Deliberate bug to test debug hooks on Python memory allocators:
3668+
call PyObject_Malloc() without holding the GIL */
36513669
Py_BEGIN_ALLOW_THREADS
36523670
buffer = PyObject_Malloc(10);
36533671
Py_END_ALLOW_THREADS
@@ -3841,6 +3859,7 @@ static PyMethodDef TestMethods[] = {
38413859
{"get_recursion_depth", get_recursion_depth, METH_NOARGS},
38423860
{"pymem_buffer_overflow", pymem_buffer_overflow, METH_NOARGS},
38433861
{"pymem_api_misuse", pymem_api_misuse, METH_NOARGS},
3862+
{"pymem_malloc_without_gil", pymem_malloc_without_gil, METH_NOARGS},
38443863
{"pyobject_malloc_without_gil", pyobject_malloc_without_gil, METH_NOARGS},
38453864
{NULL, NULL} /* sentinel */
38463865
};

Objects/obmalloc.c

Lines changed: 7 additions & 7 deletions

0 commit comments

Comments
 (0)