Skip to content

Commit

Permalink
Merge pull request #25426 from ngoldbaum/set-invalid-state
Browse files Browse the repository at this point in the history
BUG: avoid seg fault from OOB access in RandomState.set_state()
  • Loading branch information
seberg committed Dec 19, 2023
2 parents b9a0c9e + 952fac6 commit 0032ede
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
19 changes: 10 additions & 9 deletions numpy/random/mtrand.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -368,15 +368,16 @@ cdef class RandomState:
else:
if not isinstance(state, (tuple, list)):
raise TypeError('state must be a dict or a tuple.')
if state[0] != 'MT19937':
raise ValueError('set_state can only be used with legacy MT19937'
'state instances.')
st = {'bit_generator': state[0],
'state': {'key': state[1], 'pos': state[2]}}
if len(state) > 3:
st['has_gauss'] = state[3]
st['gauss'] = state[4]
value = st
with cython.boundscheck(True):
if state[0] != 'MT19937':
raise ValueError('set_state can only be used with legacy '
'MT19937 state instances.')
st = {'bit_generator': state[0],
'state': {'key': state[1], 'pos': state[2]}}
if len(state) > 3:
st['has_gauss'] = state[3]
st['gauss'] = state[4]
value = st

self._aug_state.gauss = st.get('gauss', 0.0)
self._aug_state.has_gauss = st.get('has_gauss', 0)
Expand Down
5 changes: 5 additions & 0 deletions numpy/random/tests/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,11 @@ def test_negative_binomial(self):
# arguments without truncation.
self.prng.negative_binomial(0.5, 0.5)

def test_set_invalid_state(self):
# gh-25402
with pytest.raises(IndexError):
self.prng.set_state(())


class TestRandint:

Expand Down

0 comments on commit 0032ede

Please sign in to comment.