From 6877987002684465d30b349759285648824553da Mon Sep 17 00:00:00 2001 From: Angus Gratton Date: Wed, 27 Mar 2024 17:25:25 +1100 Subject: [PATCH] tests/cpydiff: Add a note about risk of resizing memoryview targets. This a stop-gap until there is a proper fix for this. This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton --- tests/cpydiff/types_memoryview_invalid.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 tests/cpydiff/types_memoryview_invalid.py diff --git a/tests/cpydiff/types_memoryview_invalid.py b/tests/cpydiff/types_memoryview_invalid.py new file mode 100644 index 0000000000..c995a2e899 --- /dev/null +++ b/tests/cpydiff/types_memoryview_invalid.py @@ -0,0 +1,12 @@ +""" +categories: Types,memoryview +description: memoryview can become invalid if its target is resized +cause: CPython prevents a ``bytearray`` or ``io.bytesIO`` object from changing size while there is a ``memoryview`` object that references it. MicroPython requires the programmer to manually ensure that an object is not resized while any ``memoryview`` references it. + +In the worst case scenario, resizing an object which is the target of a memoryview can cause the memoryview(s) to reference invalid freed memory (a use-after-free bug) and corrupt the MicroPython runtime. +workaround: Do not change the size of any ``bytearray`` or ``io.bytesIO`` object that has a ``memoryview`` assigned to it. +""" +b = bytearray(b"abcdefg") +m = memoryview(b) +b.extend(b"hijklmnop") +print(b, bytes(m))