From f31fc9a7860f11fd5aa387165e343ec67a0b82d3 Mon Sep 17 00:00:00 2001 From: Mohammed Talha Date: Fri, 4 Dec 2026 20:02:56 +0530 Subject: [PATCH 1/5] gh-162539: Add a pin count to ctypes objects and check it in resize() ctypes.resize() can move or free an object's memory block while other code still uses an address inside it. Add a pin count on the object that owns the memory, helpers to pin and unpin it (atomic on the free-threaded build), and make resize() raise BufferError while the block is pinned. This is groundwork only: nothing pins yet. Follow-up commits pin the block during stores, for sub-objects, for exported buffers and for pointers. The counter fits in existing padding, so objects do not grow on 64-bit platforms. --- Modules/_ctypes/callproc.c | 6 ++++ Modules/_ctypes/ctypes.h | 61 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c index c8a54b0cec83a7..119d5502a51a1d 100644 --- a/Modules/_ctypes/callproc.c +++ b/Modules/_ctypes/callproc.c @@ -2090,6 +2090,12 @@ _ctypes_resize_impl(PyObject *module, CDataObject *obj, Py_ssize_t size) "Memory cannot be resized because this object doesn't own it"); return NULL; } + if (_PyCData_IsPinned(obj)) { + // gh-162539: something still uses an address inside the block. + PyErr_SetString(PyExc_BufferError, + "Memory cannot be resized while it is in use"); + return NULL; + } if ((size_t)size <= sizeof(obj->b_value)) { /* internal default buffer is large enough */ obj->b_size = size; diff --git a/Modules/_ctypes/ctypes.h b/Modules/_ctypes/ctypes.h index 98d8b660850b0d..e76516aa762042 100644 --- a/Modules/_ctypes/ctypes.h +++ b/Modules/_ctypes/ctypes.h @@ -183,6 +183,8 @@ struct tagCDataObject { PyObject_HEAD char *b_ptr; /* pointer to memory block */ int b_needsfree; /* need _we_ free the memory? */ + int b_pins; /* reasons the memory block must not move; + see _PyCData_Pin() */ CDataObject *b_base; /* pointer to base object or NULL */ Py_ssize_t b_size; /* size of memory block in bytes */ Py_ssize_t b_length; /* number of references we need */ @@ -214,6 +216,7 @@ typedef struct { PyObject_HEAD char *b_ptr; /* pointer to memory block */ int b_needsfree; /* need _we_ free the memory? */ + int b_pins; /* reasons the memory block must not move */ CDataObject *b_base; /* pointer to base object or NULL */ Py_ssize_t b_size; /* size of memory block in bytes */ Py_ssize_t b_length; /* number of references we need */ @@ -252,6 +255,64 @@ extern int PyObject_stginfo(PyObject *self, Py_ssize_t *psize, Py_ssize_t *palig #define CDataObject_Check(st, v) PyObject_TypeCheck((v), (st)->PyCData_Type) #define _CDataObject_HasExternalBuffer(v) ((v)->b_ptr != (char *)&(v)->b_value) +/* gh-162539: ctypes.resize() may move or free the memory block of an object + that owns its memory. Anything that keeps using an address inside that + block -- a store in progress, a sub-object, an exported buffer, a pointer + -- must "pin" the block first and unpin it when done. resize() refuses + while the block is pinned. + + The pin count lives on the owner: the object at the end of the b_base + chain whose block contains the address. A b_base link whose memory is + not inside the base's block (for example the object returned by a + pointer's .contents) ends the chain. + + Every _PyCData_Pin() must be balanced by exactly one _PyCData_Unpin() on + the same object, on every path including errors. */ + +static inline CDataObject * +_PyCData_MemoryOwner(CDataObject *obj) +{ + CDataObject *base = obj->b_base; + while (base != NULL + && obj->b_ptr >= base->b_ptr + && obj->b_ptr + obj->b_size <= base->b_ptr + base->b_size) + { + obj = base; + base = obj->b_base; + } + return obj; +} + +static inline void +_PyCData_Pin(CDataObject *obj) +{ + CDataObject *owner = _PyCData_MemoryOwner(obj); +#ifdef Py_GIL_DISABLED + _Py_atomic_add_int(&owner->b_pins, 1); +#else + owner->b_pins++; +#endif +} + +static inline void +_PyCData_Unpin(CDataObject *obj) +{ + CDataObject *owner = _PyCData_MemoryOwner(obj); +#ifdef Py_GIL_DISABLED + int old = _Py_atomic_add_int(&owner->b_pins, -1); +#else + int old = owner->b_pins--; +#endif + assert(old > 0); + (void)old; +} + +static inline int +_PyCData_IsPinned(CDataObject *obj) +{ + return FT_ATOMIC_LOAD_INT(obj->b_pins) > 0; +} + #define PyCSimpleTypeObject_CheckExact(st, v) Py_IS_TYPE((v), (st)->PyCSimpleType_Type) #define PyCSimpleTypeObject_Check(st, v) PyObject_TypeCheck((v), (st)->PyCSimpleType_Type) From a070532e9d88d3a672715bf853a7f1070354694e Mon Sep 17 00:00:00 2001 From: Mohammed Talha Date: Fri, 4 Dec 2026 20:12:05 +0530 Subject: [PATCH 2/5] gh-162539: Pin ctypes memory while a value is being stored Storing into a structure field, an array item or the value of a simple type converts the Python value after the destination address has been computed. The conversion can run Python code (__index__, __float__, __bool__, or calling a structure type for a tuple), and if that code called ctypes.resize() on the object, the store wrote into the freed memory block. Pin the object that owns the memory for the duration of the store in PyCData_set() and in the value setter of simple types, so resize() raises BufferError instead. Writes through a sub-object pin the outer object that owns the memory. --- Lib/test/test_ctypes/test_varsize_struct.py | 107 +++++++++++++++++- ...-12-04-12-00-00.gh-issue-162539.rZ8kQw.rst | 4 + Modules/_ctypes/_ctypes.c | 7 ++ 3 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-12-04-12-00-00.gh-issue-162539.rZ8kQw.rst diff --git a/Lib/test/test_ctypes/test_varsize_struct.py b/Lib/test/test_ctypes/test_varsize_struct.py index 3e6ba6fed07e74..1a64a259c72888 100644 --- a/Lib/test/test_ctypes/test_varsize_struct.py +++ b/Lib/test/test_ctypes/test_varsize_struct.py @@ -1,5 +1,6 @@ import unittest -from ctypes import Structure, sizeof, resize, c_int +from ctypes import (Structure, sizeof, resize, c_int, c_longlong, c_double, + c_bool, c_uint32, c_char) class VarSizeTest(unittest.TestCase): @@ -48,5 +49,109 @@ def test_zerosized_array(self): self.assertRaises(IndexError, array.__getitem__, -1) +class ResizeDuringStoreTest(unittest.TestCase): + # gh-162539: converting the value being stored can run Python code. + # If that code resized the object, the store wrote into the freed + # memory block. resize() must refuse while a store is running. + + BIG = 1 << 20 + + def resizer(self, target, value): + test = self + class Resizer: + def _resize(self): + with test.assertRaises(BufferError): + resize(target, test.BIG) + def __index__(self): + self._resize() + return value + def __float__(self): + self._resize() + return float(value) + def __bool__(self): + self._resize() + return bool(value) + return Resizer() + + def check_released(self, owner): + # The store is over, so the memory can be resized again. + resize(owner, self.BIG) + self.assertEqual(sizeof(owner), self.BIG) + + def test_structure_field(self): + class S(Structure): + _fields_ = [("pad", c_char * 4080), ("val", c_longlong)] + s = S() + s.val = self.resizer(s, 42) + self.assertEqual(s.val, 42) + self.check_released(s) + + def test_structure_field_float_and_bool(self): + class S(Structure): + _fields_ = [("d", c_double), ("b", c_bool)] + s = S() + s.d = self.resizer(s, 1.5) + s.b = self.resizer(s, 1) + self.assertEqual((s.d, s.b), (1.5, True)) + self.check_released(s) + + def test_bit_field(self): + class S(Structure): + _fields_ = [("pad", c_uint32), ("val", c_uint32, 5)] + s = S() + s.val = self.resizer(s, 3) + self.assertEqual(s.val, 3) + self.check_released(s) + + def test_array_item(self): + a = (c_longlong * 600)() + a[599] = self.resizer(a, 7) + self.assertEqual(a[599], 7) + self.check_released(a) + + def test_simple_value(self): + v = c_longlong() + resize(v, 4096) + v.value = self.resizer(v, 9) + self.assertEqual(v.value, 9) + self.check_released(v) + + def test_nested_structure_field(self): + # The store goes through a sub-object; the outer object owns the + # memory and is the one that must not be resized. + class P(Structure): + _fields_ = [("x", c_longlong)] + class S(Structure): + _fields_ = [("pad", c_char * 4080), ("p", P)] + s = S() + s.p.x = self.resizer(s, 5) + self.assertEqual(s.p.x, 5) + self.check_released(s) + + def test_tuple_to_structure(self): + # A tuple is converted by calling the field's type with it. + class P(Structure): + _fields_ = [("x", c_longlong)] + class S(Structure): + _fields_ = [("pad", c_char * 4080), ("p", P)] + s = S() + s.p = (self.resizer(s, 6),) + self.assertEqual(s.p.x, 6) + self.check_released(s) + + def test_failed_conversion_releases(self): + class Bad: + def __index__(self): + raise ZeroDivisionError + v = c_int() + with self.assertRaises(ZeroDivisionError): + v.value = Bad() + a = (c_int * 4)() + with self.assertRaises(ZeroDivisionError): + a[0] = Bad() + self.check_released(v) + self.check_released(a) + + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Library/2026-12-04-12-00-00.gh-issue-162539.rZ8kQw.rst b/Misc/NEWS.d/next/Library/2026-12-04-12-00-00.gh-issue-162539.rZ8kQw.rst new file mode 100644 index 00000000000000..997ec6abfb5904 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-04-12-00-00.gh-issue-162539.rZ8kQw.rst @@ -0,0 +1,4 @@ +Fix a use-after-free in :mod:`ctypes` when converting a value stored into a +structure field, an array item or the ``value`` of a simple type calls +:func:`ctypes.resize` on the object being written to. :func:`!resize` now +raises :exc:`BufferError` while a store into the object is in progress. diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index 301c28d2eb2115..805bd321cc4c35 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -3641,8 +3641,12 @@ PyCData_set(ctypes_state *st, return -1; } + // gh-162539: converting value can run Python code; keep the memory + // block (and so ptr) from being moved by ctypes.resize() meanwhile. + _PyCData_Pin(mem); result = _PyCData_set(st, mem, type, setfunc, value, size, ptr); + _PyCData_Unpin(mem); if (result == NULL) return -1; @@ -5540,7 +5544,10 @@ _ctypes_Simple_value_set_impl(CDataObject *self, PyObject *value) assert(info); /* Cannot be NULL for CDataObject instances */ assert(info->setfunc); + // gh-162539: see PyCData_set(). + _PyCData_Pin(self); result = info->setfunc(self->b_ptr, value, info->size); + _PyCData_Unpin(self); if (!result) return -1; From d60658f0d23397d25e91ba49701c990f7d7dd31e Mon Sep 17 00:00:00 2001 From: Mohammed Talha Date: Fri, 4 Dec 2026 20:20:02 +0530 Subject: [PATCH 3/5] gh-162539: Document that ctypes.resize() can move the buffer Like realloc(), resize() may move the memory block, so pointers, byref() results and addresses taken before the call become invalid. ctypes cannot track raw addresses, so this is documented rather than enforced. Also document the BufferError raised while the buffer is in use. --- Doc/library/ctypes.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst index b62bd94893c285..efb312eb9c6caa 100644 --- a/Doc/library/ctypes.rst +++ b/Doc/library/ctypes.rst @@ -2490,6 +2490,17 @@ Utility functions than the native size of the objects type, as given by ``sizeof(type(obj))``, but it is possible to enlarge the buffer. + Like the C ``realloc()`` function, resizing may move the buffer to a new + address. Pointers into the old buffer, such as those created with + :func:`pointer`, :func:`cast` or :func:`byref`, and addresses returned by + :func:`addressof`, are no longer valid after the call and must not be used. + + :exc:`BufferError` is raised if the buffer is in use and cannot be moved, + for example while a value is being stored into *obj*. + + .. versionchanged:: next + Raise :exc:`BufferError` instead of moving a buffer that is in use. + .. function:: set_errno(value) From 6f59c3142e72fc4777390d0da091cea417bbc7ce Mon Sep 17 00:00:00 2001 From: Mohammed Talha Date: Fri, 4 Dec 2026 20:42:01 +0530 Subject: [PATCH 4/5] gh-162539: Define the ctypes pin helpers in _ctypes.c Move the pin and unpin helpers from static inline functions in ctypes.h to extern functions in _ctypes.c, as suggested in review. --- Modules/_ctypes/_ctypes.c | 46 +++++++++++++++++++++++++++++++++++++++ Modules/_ctypes/ctypes.h | 46 +++------------------------------------ 2 files changed, 49 insertions(+), 43 deletions(-) diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index 805bd321cc4c35..bb76c2fc573690 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -3621,6 +3621,52 @@ _PyCData_set(ctypes_state *st, return NULL; } +/* gh-162539: pinning the memory block of a ctypes object; see ctypes.h. */ + +static CDataObject * +cdata_memory_owner(CDataObject *obj) +{ + CDataObject *base = obj->b_base; + while (base != NULL + && obj->b_ptr >= base->b_ptr + && obj->b_ptr + obj->b_size <= base->b_ptr + base->b_size) + { + obj = base; + base = obj->b_base; + } + return obj; +} + +void +_PyCData_Pin(CDataObject *obj) +{ + CDataObject *owner = cdata_memory_owner(obj); +#ifdef Py_GIL_DISABLED + _Py_atomic_add_int(&owner->b_pins, 1); +#else + owner->b_pins++; +#endif +} + +void +_PyCData_Unpin(CDataObject *obj) +{ + CDataObject *owner = cdata_memory_owner(obj); +#ifdef Py_GIL_DISABLED + int old = _Py_atomic_add_int(&owner->b_pins, -1); +#else + int old = owner->b_pins--; +#endif + assert(old > 0); + (void)old; +} + +int +_PyCData_IsPinned(CDataObject *obj) +{ + return FT_ATOMIC_LOAD_INT(obj->b_pins) > 0; +} + /* * Set a slice in object 'dst', which has the type 'type', * to the value 'value'. diff --git a/Modules/_ctypes/ctypes.h b/Modules/_ctypes/ctypes.h index e76516aa762042..92d6f87a307ca3 100644 --- a/Modules/_ctypes/ctypes.h +++ b/Modules/_ctypes/ctypes.h @@ -269,49 +269,9 @@ extern int PyObject_stginfo(PyObject *self, Py_ssize_t *psize, Py_ssize_t *palig Every _PyCData_Pin() must be balanced by exactly one _PyCData_Unpin() on the same object, on every path including errors. */ -static inline CDataObject * -_PyCData_MemoryOwner(CDataObject *obj) -{ - CDataObject *base = obj->b_base; - while (base != NULL - && obj->b_ptr >= base->b_ptr - && obj->b_ptr + obj->b_size <= base->b_ptr + base->b_size) - { - obj = base; - base = obj->b_base; - } - return obj; -} - -static inline void -_PyCData_Pin(CDataObject *obj) -{ - CDataObject *owner = _PyCData_MemoryOwner(obj); -#ifdef Py_GIL_DISABLED - _Py_atomic_add_int(&owner->b_pins, 1); -#else - owner->b_pins++; -#endif -} - -static inline void -_PyCData_Unpin(CDataObject *obj) -{ - CDataObject *owner = _PyCData_MemoryOwner(obj); -#ifdef Py_GIL_DISABLED - int old = _Py_atomic_add_int(&owner->b_pins, -1); -#else - int old = owner->b_pins--; -#endif - assert(old > 0); - (void)old; -} - -static inline int -_PyCData_IsPinned(CDataObject *obj) -{ - return FT_ATOMIC_LOAD_INT(obj->b_pins) > 0; -} +extern void _PyCData_Pin(CDataObject *obj); +extern void _PyCData_Unpin(CDataObject *obj); +extern int _PyCData_IsPinned(CDataObject *obj); #define PyCSimpleTypeObject_CheckExact(st, v) Py_IS_TYPE((v), (st)->PyCSimpleType_Type) #define PyCSimpleTypeObject_Check(st, v) PyObject_TypeCheck((v), (st)->PyCSimpleType_Type) From 38b291655feb21b5a13357bc07a0e7f6b966fac7 Mon Sep 17 00:00:00 2001 From: Aaquib Date: Fri, 4 Dec 2026 21:19:56 +0530 Subject: [PATCH 5/5] gh-162539: Pin the base while a ctypes sub-object is alive A sub-object such as s.field or array[i] points into its base's memory block. If ctypes.resize() moved or freed that block while the sub-object was alive, the sub-object kept using freed memory. Pin the base when such a sub-object is created and unpin it when the sub-object is cleared, so resize() raises BufferError while any sub-object of the block is alive. A sub-object whose memory is not inside its base's block, such as a pointer's .contents, does not pin. --- Lib/test/test_ctypes/test_resize_pins.py | 179 +++++++++++++++++++++++ Modules/_ctypes/_ctypes.c | 63 +++++++- 2 files changed, 241 insertions(+), 1 deletion(-) create mode 100644 Lib/test/test_ctypes/test_resize_pins.py diff --git a/Lib/test/test_ctypes/test_resize_pins.py b/Lib/test/test_ctypes/test_resize_pins.py new file mode 100644 index 00000000000000..de462050b09179 --- /dev/null +++ b/Lib/test/test_ctypes/test_resize_pins.py @@ -0,0 +1,179 @@ +import threading +import unittest +from ctypes import (Structure, Union, sizeof, resize, pointer, + c_int, c_longlong, c_char) +from test.support import disable_gc, gc_collect, threading_helper + + +BIG = 1 << 20 + + +class Inner(Structure): + _fields_ = [("x", c_longlong)] + + +class Middle(Structure): + _fields_ = [("pad", c_char * 16), ("inner", Inner)] + + +class Outer(Structure): + _fields_ = [("pad", c_char * 4080), ("middle", Middle), ("n", c_int)] + + +class ResizeWithSubObjectTest(unittest.TestCase): + # gh-162539: a sub-object such as ``s.field`` or ``array[i]`` points + # into the memory block of the object it came from. resize() may move + # or free that block, so it must refuse while a sub-object is alive. + + def check_resizable(self, owner): + resize(owner, BIG) + self.assertEqual(sizeof(owner), BIG) + + def test_structure_field(self): + s = Outer() + middle = s.middle + self.assertRaises(BufferError, resize, s, BIG) + self.assertEqual(sizeof(s), sizeof(Outer)) + middle.inner.x = 5 # still writes into s's memory + self.assertEqual(s.middle.inner.x, 5) + del middle + self.check_resizable(s) + self.assertEqual(s.middle.inner.x, 5) + + def test_union_field(self): + class U(Union): + _fields_ = [("inner", Inner), ("n", c_int)] + u = U() + inner = u.inner + self.assertRaises(BufferError, resize, u, BIG) + del inner + self.check_resizable(u) + + def test_nested_sub_object(self): + s = Outer() + inner = s.middle.inner # the temporary s.middle is freed here + self.assertRaises(BufferError, resize, s, BIG) + del inner + self.check_resizable(s) + + def test_nested_sub_object_keeps_chain_pinned(self): + s = Outer() + middle = s.middle + inner = middle.inner + del middle # inner still references it + self.assertRaises(BufferError, resize, s, BIG) + del inner + self.check_resizable(s) + + def test_array_item(self): + a = (Inner * 600)() + item = a[599] + self.assertRaises(BufferError, resize, a, BIG) + del item + self.check_resizable(a) + + def test_array_slice_items(self): + # Slicing an array of structures returns a list of sub-objects. + a = (Inner * 4)() + items = a[1:3] + self.assertRaises(BufferError, resize, a, BIG) + del items + self.check_resizable(a) + + def test_array_of_arrays(self): + a = (c_int * 4 * 300)() + row = a[299] + self.assertRaises(BufferError, resize, a, BIG) + del row + self.check_resizable(a) + + def test_many_sub_objects(self): + s = Outer() + subs = [s.middle for _ in range(10)] + for _ in range(9): + subs.pop() + self.assertRaises(BufferError, resize, s, BIG) + subs.pop() + self.check_resizable(s) + + def test_simple_field_is_not_a_sub_object(self): + # Fields of simple types return Python values, not sub-objects. + s = Outer() + n = s.n + x = s.middle.inner.x + self.check_resizable(s) + self.assertEqual((n, x), (0, 0)) + + def test_temporary_sub_objects(self): + s = Outer() + s.middle.inner.x = 7 + self.assertEqual(s.middle.inner.x, 7) + self.check_resizable(s) + + def test_pointer_contents_do_not_pin_the_pointer(self): + # The memory of p.contents and p[0] belongs to the pointed-to + # object, not to the pointer, so the pointer itself can be resized. + p = pointer(Inner()) + contents = p.contents + item = p[0] + self.check_resizable(p) + del contents, item + + def test_sub_object_in_reference_cycle(self): + # The garbage collector may clear the owner before the sub-object. + # Either order must leave the objects in a consistent state. + for _ in range(20): + s = Outer() + middle = s.middle + s.ref = middle # s -> __dict__ -> middle -> s + del s, middle + gc_collect() + + def test_sub_object_released_by_gc(self): + s = Outer() + with disable_gc(): + middle = s.middle + holder = [middle] + holder.append(holder) # a cycle that only the GC frees + del middle, holder + self.assertRaises(BufferError, resize, s, BIG) + gc_collect() + self.check_resizable(s) + + @threading_helper.requires_working_threading() + def test_concurrent_sub_objects_and_resize(self): + # resize() must either succeed or raise BufferError, and never + # move the block under a sub-object that is being used. + a = (Inner * 64)() + results = [] + stop = threading.Event() + + def reader(): + while not stop.is_set(): + item = a[63] + item.x += 1 + del item + + def resizer(): + outcomes = set() + for i in range(2000): + try: + resize(a, sizeof(Inner * 64) + (16 if i & 1 else 4096)) + outcomes.add("ok") + except BufferError: + outcomes.add("pinned") + results.append(outcomes) + + readers = [threading.Thread(target=reader) for _ in range(4)] + resizers = [threading.Thread(target=resizer) for _ in range(2)] + with threading_helper.start_threads(readers + resizers): + for t in resizers: + t.join() + stop.set() + self.assertEqual(len(results), 2) + for outcomes in results: + self.assertLessEqual(outcomes, {"ok", "pinned"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index bb76c2fc573690..daddaa6bafd26c 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -3115,10 +3115,58 @@ PyCData_traverse(PyObject *op, visitproc visit, void *arg) return 0; } +/* gh-162539: a sub-object (for example s.field or array[i] of a structure, + union or array type) points into its base's memory block, so it pins the + block for as long as it lives; see PyCData_FromBaseObj(). + + The pin is counted on the immediate base, not on the block's owner: every + object on the b_base chain holds a reference to the next one, so the + owner stays pinned while any sub-object is alive. This also keeps the + unpin in PyCData_clear() right when the garbage collector clears the base + (and sets its b_ptr to NULL) before the sub-object; the owner found from + the addresses at that point would be the wrong object. + + As in _PyCData_MemoryOwner(), a sub-object whose memory is not inside + the base's block (a pointer's .contents or p[i]) does not pin the base. */ +static int +PyCData_SubObjectPinsBase(CDataObject *base, char *adr, Py_ssize_t size) +{ + return (base->b_ptr != NULL + && adr >= base->b_ptr + && adr + size <= base->b_ptr + base->b_size); +} + +static void +PyCData_PinBase(CDataObject *base) +{ +#ifdef Py_GIL_DISABLED + _Py_atomic_add_int(&base->b_pins, 1); +#else + base->b_pins++; +#endif +} + +static void +PyCData_UnpinBase(CDataObject *base) +{ +#ifdef Py_GIL_DISABLED + int old = _Py_atomic_add_int(&base->b_pins, -1); +#else + int old = base->b_pins--; +#endif + assert(old > 0); + (void)old; +} + static int PyCData_clear(PyObject *op) { CDataObject *self = _CDataObject_CAST(op); + if (self->b_base != NULL + && PyCData_SubObjectPinsBase(self->b_base, self->b_ptr, self->b_size)) + { + PyCData_UnpinBase(self->b_base); + } Py_CLEAR(self->b_objects); if ((self->b_needsfree) && _CDataObject_HasExternalBuffer(self)) @@ -3401,15 +3449,28 @@ PyCData_FromBaseObj(ctypes_state *st, } stginfo_set_dict_final(info); + // gh-162539: pin before tp_alloc(), which can run the GC and so let + // another thread resize base between computing adr and pinning. + int pinned = 0; + if (base) { + assert(CDataObject_Check(st, base)); + pinned = PyCData_SubObjectPinsBase((CDataObject *)base, adr, + info->size); + if (pinned) { + PyCData_PinBase((CDataObject *)base); + } + } cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0); if (cmem == NULL) { + if (pinned) { + PyCData_UnpinBase((CDataObject *)base); + } return NULL; } assert(CDataObject_Check(st, cmem)); cmem->b_length = info->length; cmem->b_size = info->size; if (base) { /* use base's buffer */ - assert(CDataObject_Check(st, base)); cmem->b_ptr = adr; cmem->b_needsfree = 0; cmem->b_base = (CDataObject *)Py_NewRef(base);