summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2022-10-02 04:18:38 (GMT)
committerGitHub <noreply@github.com>2022-10-02 04:18:38 (GMT)
commitc6fcbb4928ced97df81d2cef6c5dcec6bc7dcab7 (patch)
tree7d222d7c3d8d1a339754a290a4e2ee631dda526c /Lib
parenta4fbb949659b86b0925b20a9ef6bc2877f397252 (diff)
downloadcpython-c6fcbb4928ced97df81d2cef6c5dcec6bc7dcab7.zip
cpython-c6fcbb4928ced97df81d2cef6c5dcec6bc7dcab7.tar.gz
cpython-c6fcbb4928ced97df81d2cef6c5dcec6bc7dcab7.tar.bz2
gh-97591: In `Exception.__setstate__()` acquire strong references before calling `tp_hash` slot (GH-97700)
(cherry picked from commit d63943860974f232b5f027dc6535d25d1b4d8fc0) Co-authored-by: Ofey Chan <ofey206@gmail.com>
Diffstat (limited to 'Lib')
-rw-r--r--Lib/test/test_baseexception.py25
1 files changed, 25 insertions, 0 deletions
diff --git a/Lib/test/test_baseexception.py b/Lib/test/test_baseexception.py
index 8db497a..018626e 100644
--- a/Lib/test/test_baseexception.py
+++ b/Lib/test/test_baseexception.py
@@ -114,6 +114,31 @@ class ExceptionClassTests(unittest.TestCase):
[repr(exc), exc.__class__.__name__ + '()'])
self.interface_test_driver(results)
+ def test_setstate_refcount_no_crash(self):
+ # gh-97591: Acquire strong reference before calling tp_hash slot
+ # in PyObject_SetAttr.
+ import gc
+ d = {}
+ class HashThisKeyWillClearTheDict(str):
+ def __hash__(self) -> int:
+ d.clear()
+ return super().__hash__()
+ class Value(str):
+ pass
+ exc = Exception()
+
+ d[HashThisKeyWillClearTheDict()] = Value() # refcount of Value() is 1 now
+
+ # Exception.__setstate__ should aquire a strong reference of key and
+ # value in the dict. Otherwise, Value()'s refcount would go below
+ # zero in the tp_hash call in PyObject_SetAttr(), and it would cause
+ # crash in GC.
+ exc.__setstate__(d) # __hash__() is called again here, clearing the dict.
+
+ # This GC would crash if the refcount of Value() goes below zero.
+ gc.collect()
+
+
class UsageTests(unittest.TestCase):
"""Test usage of exceptions"""