Skip to content
Closed
Show file tree
Hide file tree
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
11 changes: 11 additions & 0 deletions Doc/library/ctypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
179 changes: 179 additions & 0 deletions Lib/test/test_ctypes/test_resize_pins.py
Original file line number Diff line number Diff line change
@@ -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()
107 changes: 106 additions & 1 deletion Lib/test/test_ctypes/test_varsize_struct.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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()
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading