Skip to content

BUG: non integer overlap might lead to corrupt memory access in as_strided [backport 1.4.x] #3845

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 26, 2014
Merged
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
9 changes: 9 additions & 0 deletions lib/matplotlib/mlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,11 @@ def stride_windows(x, n, noverlap=None, axis=0):
if n > x.size:
raise ValueError('n cannot be greater than the length of x')

# np.lib.stride_tricks.as_strided easily leads to memory corruption for
# non integer shape and strides, i.e. noverlap or n. See #3845.
noverlap = int(noverlap)
n = int(n)

step = n - noverlap
if axis == 0:
shape = (n, (x.shape[-1]-noverlap)//step)
Expand Down Expand Up @@ -642,6 +647,10 @@ def stride_repeat(x, n, axis=0):
if n < 1:
raise ValueError('n cannot be less than 1')

# np.lib.stride_tricks.as_strided easily leads to memory corruption for
# non integer shape and strides, i.e. n. See #3845.
n = int(n)

if axis == 0:
shape = (n, x.size)
strides = (0, x.strides[0])
Expand Down
18 changes: 18 additions & 0 deletions lib/matplotlib/tests/test_mlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,24 @@ def test_stride_windows_n32_noverlap0_axis1_unflatten(self):
assert_equal(y.shape, x1.shape)
assert_array_equal(y, x1)

def test_stride_ensure_integer_type(self):
N = 100
x = np.empty(N + 20, dtype='>f4')
x.fill(np.NaN)
y = x[10:-10]
y.fill(0.3)
# previous to #3845 lead to corrupt access
y_strided = mlab.stride_windows(y, n=33, noverlap=0.6)
assert_array_equal(y_strided, 0.3)
# previous to #3845 lead to corrupt access
y_strided = mlab.stride_windows(y, n=33.3, noverlap=0)
assert_array_equal(y_strided, 0.3)
# even previous to #3845 could not find any problematic
# configuration however, let's be sure it's not accidentally
# introduced
y_strided = mlab.stride_repeat(y, n=33.815)
assert_array_equal(y_strided, 0.3)


class csv_testcase(CleanupTestCase):
def setUp(self):
Expand Down