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) 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/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..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); @@ -3621,6 +3682,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'. @@ -3641,8 +3748,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 +5651,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; 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..92d6f87a307ca3 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,24 @@ 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. */ + +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)