-
- Downloads
python: Accept buffers in nbd.Buffer.from_bytearray()
Prior to this patch, the following fails, but at least seems to give a
sensible error:
$ nbdsh -c 'nbd.Buffer.from_bytearray(b"1"*8)'
Traceback (most recent call last):
File "/usr/lib64/python3.10/runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib64/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/usr/lib64/python3.10/site-packages/nbd.py", line 2726, in <module>
nbdsh.shell()
File "/usr/lib64/python3.10/site-packages/nbdsh.py", line 139, in shell
exec(c, d, d)
File "<string>", line 1, in <module>
File "/usr/lib64/python3.10/site-packages/nbd.py", line 132, in from_bytearray
o = libnbdmod.aio_buffer_from_bytearray(ba)
RuntimeError: parameter is not a bytearray
while this version 1 byte longer flat out segfaults:
$ nbdsh -c 'nbd.Buffer.from_bytearray(b"1"*9)'
and this one is subtly different:
$ nbdsh -c 'nbd.Buffer.from_bytearray(h)'
Traceback (most recent call last):
...
File "/usr/lib64/python3.10/site-packages/nbd.py", line 132, in from_bytearray
o = libnbdmod.aio_buffer_from_bytearray(ba)
MemoryError
That's because PyByteArray_AsString() blindly assumes that its
argument is a PyByteArray, and goes haywire when it is not, unless we
got lucky that the incorrectly-typed object behaves similarly enough
(which, for byte literals, is size-dependent).
But Python already has a handy way to convert any object that supports
the buffer interface into a bytearray. Using it, we can now support
many more parameters; passing in b"1"*9 now correctly creates a 9-byte
buffer rather than failing. And the error message for a non-buffer
also improves:
$ ./run nbdsh -c 'nbd.Buffer.from_bytearray(h)'
Traceback (most recent call last):
...
File "/home/eblake/libnbd/python/nbd.py", line 132, in from_bytearray
o = libnbdmod.aio_buffer_from_bytearray(ba)
TypeError: cannot convert 'NBD' object to bytearray
Now we get a reliable TypeError, which is always better than an
unexpected MemoryError or segfault.
Also update unit test 580 to cover more buffer functions.
It may still be worth a future API change to use PyMemoryView for less
copying in and out of C structures and thus more performance, but
that's a bigger task.
Reviewed-by:
Richard W.M. Jones <rjones@redhat.com>
Loading