Skip to content

bpo-31478: Fix an assertion failure in random.seed() in case the 'a' arg has a bad __abs__() method #3596

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 5 commits into from
Sep 28, 2017
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
11 changes: 11 additions & 0 deletions Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,17 @@ def test_bug_27706(self):
['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
'0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])

def test_bug_31478(self):
# There shouldn't be an assertion failure in _random.Random.seed() in
# case the argument has a bad __abs__() method.
class BadInt(int):
def __abs__(self):
return None
try:
self.gen.seed(BadInt())
except TypeError:
pass

def test_bug_31482(self):
# Verify that version 1 seeds are unaffected by hash randomization
# when the seeds are expressed as bytes rather than strings.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix an assertion failure in `_random.Random.seed()` in case the argument has a
bad ``__abs__()`` method. Patch by Oren Milman.
7 changes: 5 additions & 2 deletions Modules/_randommodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,11 @@ random_seed(RandomObject *self, PyObject *args)
* So: if the arg is a PyLong, use its absolute value.
* Otherwise use its hash value, cast to unsigned.
*/
if (PyLong_Check(arg))
n = PyNumber_Absolute(arg);
if (PyLong_Check(arg)) {
/* Calling int.__abs__() prevents calling arg.__abs__(), which might
return an invalid value. See issue #31478. */
n = PyLong_Type.tp_as_number->nb_absolute(arg);
}
else {
Py_hash_t hash = PyObject_Hash(arg);
if (hash == -1)
Expand Down