Clairfy the buffer ownership test
from wasmer import Instance, Module, Store, Memory, MemoryType, Buffer, Uint8Array, Int8Array, Uint16Array, Int16Array, Uint32Array, Int32Array
import ctypes
+import gc
import inspect
import os
import pytest
@@ -299,8 +300,25 @@ def test_memory_buffer_supports_ctypes():
assert byte_array[3] == 0b01000000
def test_memory_buffer_supports_keeps_object_alive():
- # IMPL NOTE: make sure the memory instance is immediately del'd
- view = memoryview(instance().exports.memory.buffer)
+ """Overwrites a buffer's memory to segfault for incorrect ownership.
+
+ The buffer protocol requires the buffer view to keep the owner of the
+ memory ("buffer" in the example below) alive while the buffer is accessed.
+ The memoryview object only stores the buffer view and does not keep an
+ extra reference to the owner (in contrast to numpy arrays). Hence it relies
+ on correct use of the buffer protocol.
+
+ In case of incorrect ownership semantics, the write operation below would
+ write into free'd memory. Depending on architecture, this operation will
+ lead to a segfault.
+ """
+ buffer = instance().exports.memory.buffer
+ view = memoryview(buffer)
+
+ # delete the buffer and call the GC to force the buffer view held inside
+ # the view object to be the only reference to the buffer object
+ del buffer
+ gc.collect()
val = bytes([42] * 1024)
for i in range(len(view) // 1024):
