From 55235c7d8f48e56aa18c8f4152b984b80a7d63f9 Mon Sep 17 00:00:00 2001 From: felixthebeard <33093597+felixthebeard@users.noreply.github.com> Date: Wed, 6 Sep 2023 21:40:33 +0200 Subject: [PATCH] Fix unsafe loading from file buffer (#58) * Fix unsafe loading from file buffer The numpy documentation states for numpy.frombuffer` that: > This function creates a view into the original object. > This should be safe in general, but it may make sense to copy > the result when the original object is mutable or untrusted. When the filebuffer is mutable a `ValueError: output array is read-only` is raised in: https://github.com/eyurtsev/fcsparser/blob/701000af178e36e0dedb53d409119c25675b9d16/fcsparser/api.py#L590 * Update pyproject.toml --------- Co-authored-by: Eugene Yurtsev --- fcsparser/api.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/fcsparser/api.py b/fcsparser/api.py index fbee7d3..2947a4d 100644 --- a/fcsparser/api.py +++ b/fcsparser/api.py @@ -68,13 +68,18 @@ def fromfile(file, dtype, count, *args, **kwargs): file, dtype=",".join(["u1"] * record_width), count=count, *args, **kwargs ) except (TypeError, IOError): - ret = numpy.frombuffer( + _ret = numpy.frombuffer( file.read(count * record_width), dtype=",".join(["u1"] * record_width), count=count, *args, **kwargs ) + # Create a copy of the file content as `numpy.frombuffer` + # returns a view into the original object which is not + # safe for mutable file buffers. + # See https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html + ret = _ret.copy() # convert the DATA segment from a 1 x `count` array of records # (and remember, each record is composed of `record_width`